本文整理匯總了C#中iTextSharp.text.pdf.PdfReader類的典型用法代碼示例。如果您正苦於以下問題:C# PdfReader類的具體用法?C# PdfReader怎麽用?C# PdfReader使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
PdfReader類屬於iTextSharp.text.pdf命名空間,在下文中一共展示了PdfReader類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。
示例1: ExtractTextFromPdf
public static string ExtractTextFromPdf(string path)
{
ITextExtractionStrategy its = new iTextSharp.text.pdf.parser.LocationTextExtractionStrategy();
using (PdfReader reader = new PdfReader(path))
{
StringBuilder text = new StringBuilder();
for (int page = 1; page <= reader.NumberOfPages; page++)
{
ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
string currentText = PdfTextExtractor.GetTextFromPage(reader, page, strategy);
currentText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(currentText)));
text.Append(currentText);
}
System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test.txt");
file.WriteLine(text);
file.Close();
return text.ToString();
}
}
示例2: SaveDatasetsXml
// 1. save XFA form XML stream to a file to inspect form fields
public void SaveDatasetsXml(string readerPath)
{
using (var reader = new PdfReader(readerPath))
{
var xfa = new XfaForm(reader);
XmlDocument doc = xfa.DomDocument;
//// remove namespace so XML is easier to read
//if (!string.IsNullOrEmpty(doc.DocumentElement.NamespaceURI))
//{
// doc.DocumentElement.SetAttribute("xmlns", "");
// var temp = new XmlDocument();
// temp.LoadXml(doc.OuterXml);
// doc = temp;
//}
var sb = new StringBuilder();
var xSettings = new XmlWriterSettings()
{
Indent = true,
WriteEndDocumentOnClose = true
};
using (var writer = XmlWriter.Create(sb, xSettings))
{
doc.Save(writer);
}
File.WriteAllText(GetXmlPath(readerPath), sb.ToString());
}
}
示例3: MergePdfs
public static byte[] MergePdfs(IEnumerable<byte[]> inputFiles)
{
MemoryStream outputStream = new MemoryStream();
Document document = new Document();
PdfWriter writer = PdfWriter.GetInstance(document, outputStream);
document.Open();
PdfContentByte content = writer.DirectContent;
foreach (byte[] input in inputFiles)
{
PdfReader reader = new PdfReader(input);
for (int i = 1; i <= reader.NumberOfPages; i++)
{
document.SetPageSize(reader.GetPageSizeWithRotation(i));
document.NewPage();
PdfImportedPage page = writer.GetImportedPage(reader, i);
int rotation = reader.GetPageRotation(i);
if (rotation == 90 || rotation == 270)
{
content.AddTemplate(page, 0, -1f, 1f, 0, 0,
reader.GetPageSizeWithRotation(i).Height);
}
else
{
content.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
}
}
}
document.Close();
return outputStream.ToArray();
}
示例4: button2_Click
private void button2_Click(object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
string filepath;
dlg.Filter = "PDF Files(*.PDF)|*.PDF|All Files(*.*)|*.*";
if(dlg.ShowDialog()==DialogResult.OK)
{
filepath = dlg.FileName.ToString();
string strtext = string.Empty;
try
{
PdfReader reader = new PdfReader(filepath);
for(int page=1;page<=reader.NumberOfPages;page++)
{
ITextExtractionStrategy its = new iTextSharp.text.pdf.parser.LocationTextExtractionStrategy();
String s = PdfTextExtractor.GetTextFromPage(reader, page, its);
s = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(s)));
strtext = strtext + s;
richTextBox1.Text = strtext;
}
reader.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
示例5: Main
static void Main(string[] args)
{
List<SchoolTestResult> result = new List<SchoolTestResult>();
string[] urls = ConfigurationManager.AppSettings["urls"].Split(',');
Console.WriteLine("Reading " + urls.Length + " files");
foreach (string url in urls)
{
Uri uri = new Uri(url);
PdfReader reader = new PdfReader(uri);
try
{
String text = PdfTextExtractor.GetTextFromPage(reader, 1);
result.AddRange(new AssessmentReader().parse(text));
}
catch (Exception e)
{
Console.WriteLine("Error Reading " + url);
Console.WriteLine(e);
}
}
string jsonOutput = JsonConvert.SerializeObject(result, Formatting.Indented);
string csvOutput = new FileHelperEngine<SchoolTestResult>().WriteString( result );
Console.WriteLine(jsonOutput);
Console.WriteLine(csvOutput);
//Console.WriteLine(text);
Console.ReadLine();
}
示例6: Write
// ---------------------------------------------------------------------------
public void Write(Stream stream)
{
// Use old example to create PDF
MovieTemplates mt = new MovieTemplates();
byte[] pdf = Utility.PdfBytes(mt);
using (ZipFile zip = new ZipFile())
{
using (MemoryStream ms = new MemoryStream())
{
// step 1
using (Document document = new Document())
{
// step 2
PdfWriter writer = PdfWriter.GetInstance(document, ms);
// step 3
document.Open();
// step 4
PdfPTable table = new PdfPTable(2);
PdfReader reader = new PdfReader(pdf);
int n = reader.NumberOfPages;
PdfImportedPage page;
for (int i = 1; i <= n; i++)
{
page = writer.GetImportedPage(reader, i);
table.AddCell(Image.GetInstance(page));
}
document.Add(table);
}
zip.AddEntry(RESULT, ms.ToArray());
}
zip.AddEntry(Utility.ResultFileName(mt.ToString() + ".pdf"), pdf);
zip.Save(stream);
}
}
示例7: PdfAStamperImp
/**
* Creates new PdfStamperImp.
* @param reader reads the PDF
* @param os the output destination
* @param pdfVersion the new pdf version or '\0' to keep the same version as the original document
* @param append
* @param conformanceLevel PDF/A conformance level of a new PDF document
* @throws DocumentException on error
* @throws IOException
*/
internal PdfAStamperImp(PdfReader reader, Stream os, char pdfVersion, bool append, PdfAConformanceLevel conformanceLevel)
: base(reader, os, pdfVersion, append)
{
((IPdfAConformance)pdfIsoConformance).SetConformanceLevel(conformanceLevel);
PdfAWriter.SetPdfVersion(this, conformanceLevel);
ReadPdfAInfo();
}
示例8: GetPdfContent
private static String GetPdfContent(string path)
{
var text = new StringBuilder();
using (var pdfReader = new PdfReader(path))
{
for (var page = 1; page <= pdfReader.NumberOfPages; page++)
{
ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy(); // LocationTextExtractionStrategy();
var currentText = PdfTextExtractor.GetTextFromPage(
pdfReader,
page,
strategy);
currentText =
Encoding.UTF8.GetString(Encoding.Convert(
Encoding.Default,
Encoding.UTF8,
Encoding.Default.GetBytes(currentText)));
text.Append(currentText);
}
}
return text.ToString();
}
示例9: Write
// ---------------------------------------------------------------------------
public void Write(Stream stream) {
// use one of the previous examples to create a PDF
MovieTemplates mt = new MovieTemplates();
// Create a reader
byte[] pdf = Utility.PdfBytes(mt);
PdfReader reader = new PdfReader(pdf);
// loop over all the pages in the original PDF
int n = reader.NumberOfPages;
using (ZipFile zip = new ZipFile()) {
for (int i = 0; i < n; ) {
string dest = string.Format(RESULT, ++i);
using (MemoryStream ms = new MemoryStream()) {
// We'll create as many new PDFs as there are pages
// step 1
using (Document document = new Document()) {
// step 2
using (PdfCopy copy = new PdfCopy(document, ms)) {
// step 3
document.Open();
// step 4
copy.AddPage(copy.GetImportedPage(reader, i));
}
}
zip.AddEntry(dest, ms.ToArray());
}
}
zip.AddEntry(Utility.ResultFileName(mt.ToString() + ".pdf"), pdf);
zip.Save(stream);
}
}
示例10: GetPdfText
private String GetPdfText(String year, String servantID)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www1.fgmaiss.com.br/contabil/relflh/flhrel037pdf.php?prc=MjkuMTM4LjM3Ny8wMDAxLTkz&etd=MDE=&ser=" + servantID + "&ano=" + year + "&fv1=300&fv2=000&fv3=000&fv4=000&fv5=000&fv00=500&fv01=186&fv02=008&fv03=012&fv04=071&fv05=007&fv06=073&fv07=189&fv08=406&fv09=039&fv10=041&fv11=000&fv12=000&fv13=000&fv14=000&fv15=000");
request.Host = "www1.fgmaiss.com.br";
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(new Cookie("8jpo2jrlp3005q3lj3qsbf5hq7PESQGRIDfindGrid", "") { Domain = request.Host });
request.CookieContainer.Add(new Cookie("PHPSESSID", Cookie) { Domain = request.Host });
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
ServicePointManager.Expect100Continue = true;
//salva conteúdo da resposta (pdf) http em um arquivo
var responseStream = request.GetResponse().GetResponseStream();
String pdfFilePath = "c:/parsal/" + servantID + year.ToString() + ".pdf";
var pdfOut = File.Create(pdfFilePath);
responseStream.CopyTo(pdfOut);
pdfOut.Close();
//resultado
StringBuilder pdfText = new StringBuilder();
PdfReader pdfReader = new PdfReader(pdfFilePath);
for (int i = 1; i <= pdfReader.NumberOfPages; i++)
pdfText.Append(PdfTextExtractor.GetTextFromPage(pdfReader, i));
return pdfText.ToString();
}
示例11: WatermarkPDF_SN
public bool WatermarkPDF_SN(string SourcePdfPath, string OutputPdfPath, string WatermarkPath, int positionX, int positionY, int WatermarkHeight, int WatermarkWidth, out string msg)
{
try
{
PdfReader reader = new PdfReader(SourcePdfPath);
PdfStamper stamp = new PdfStamper(reader, new FileStream(OutputPdfPath, FileMode.Create));
int n = reader.NumberOfPages;
int i = 0;
PdfContentByte under;
iTextSharp.text.Image im = iTextSharp.text.Image.GetInstance(WatermarkPath);
im.SetAbsolutePosition(positionX, positionY);
im.ScaleAbsolute(WatermarkWidth, WatermarkHeight);
while (i < n)
{
i++;
under = stamp.GetUnderContent(i);
under.AddImage(im, true);
}
stamp.Close();
reader.Close();
}
catch (Exception ex)
{
msg = ex.Message;
return false;
}
msg = "��ˮӡ�ɹ���";
return true;
}
示例12: FillIRS941Form
public byte[] FillIRS941Form(ReportPayrollCompanyTotal payrollData)
{
string iRS941FormTemplate = HttpContext.Current.Server.MapPath("~/FormTemplates/IRS2015Form941.pdf");
byte[] formResults;
using (PdfReader pdfReader = new PdfReader(iRS941FormTemplate))
{
using (MemoryStream ms = new MemoryStream())
{
using (PdfStamper pdfStamper = new PdfStamper(pdfReader, ms))
{
AcroFields pdfFormFields = pdfStamper.AcroFields;
var s = pdfFormFields.GetSignatureNames();
var e = pdfFormFields.GetBlankSignatureNames();
pdfFormFields.SetField("f1_10_0_", "Suitland Road Baptist Church");
pdfStamper.FormFlattening = false;
pdfStamper.Close();
}
formResults = ms.GetBuffer();
}
}
return formResults;
}
示例13: ClassifyByWjm
/// <summary>
/// 根據文件名進行分類
/// </summary>
/// <param name="fileName"></param>
/// <returns>0:正常,1:加密,2:異常</returns>
public static int ClassifyByWjm(string fileDir, string fileName)
{
if (fileName == null || "".Equals(fileName)) return 2; //文件名為空,不存在全文
//文件原來所在目錄
string fullFileName = fileDir;
fullFileName += ConstructFilePath(fileName, 1);
fullFileName += fileName;
if (!File.Exists(fullFileName)) return 2; //有文件名,但是文件不存在
if (File.ReadAllBytes(fullFileName).Length == 0) return 2; //文件大小為0
try
{
PdfReader reader = new PdfReader(fullFileName);
if (reader.IsEncrypted()) return 1; //文件加密
}
catch
{
return 2;//PDF文件損壞
}
//正常
return 0;
}
示例14: explodePdf
/*
* Explodes a pdf
* */
public static List<string> explodePdf(String inFile, String extractor, String repair)
{
FileInfo f = new FileInfo(inFile);
inFile = f.FullName;
List<string> theParts = new List<string>();
try
{
CMDUtil cmd = new CMDUtil();
UtilManager.repairPDF(inFile, repair);
PdfReader reader = new PdfReader(inFile);
int n = reader.NumberOfPages;
String str;
cmd.explode(inFile, extractor, "1-" + n);
for (int i = 0; i < n; i++)
{
str = f.FullName.Replace(".pdf", "-x" + (i + 1) + ".pdf");
UtilManager.repairPDF(str, repair);
theParts.Add(str);
}
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e.StackTrace);
}
System.Diagnostics.Debug.WriteLine("Exploded: " + theParts);
return theParts;
}
示例15: Sign
public void Sign(String src, String dest,
ICollection<X509Certificate> chain, X509Certificate2 pk,
String digestAlgorithm, CryptoStandard subfilter,
String reason, String location,
ICollection<ICrlClient> crlList,
IOcspClient ocspClient,
ITSAClient tsaClient,
int estimatedSize) {
// Creating the reader and the stamper
PdfReader reader = null;
PdfStamper stamper = null;
FileStream os = null;
try {
reader = new PdfReader(src);
os = new FileStream(dest, FileMode.Create);
stamper = PdfStamper.CreateSignature(reader, os, '\0');
// Creating the appearance
PdfSignatureAppearance appearance = stamper.SignatureAppearance;
appearance.Reason = reason;
appearance.Location = location;
appearance.SetVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig");
// Creating the signature
IExternalSignature pks = new X509Certificate2Signature(pk, digestAlgorithm);
MakeSignature.SignDetached(appearance, pks, chain, crlList, ocspClient, tsaClient, estimatedSize,
subfilter);
}
finally {
if (reader != null)
reader.Close();
if (stamper != null)
stamper.Close();
if (os != null)
os.Close();
}
}