itextsharp使用C#在pdf文件中插入文本

时间:2012-04-10 06:22:08

标签: c# asp.net itextsharp

我想使用以下代码将文本插入带有iTextSharp的pdf文件中。很多时候它运作正常,但有时却不起作用。

FileStream pdfOutputFile = new FileStream(pdfTemplate, FileMode.Create);
PdfReader pdfReader = new PdfReader(pdffile, System.Text.Encoding.UTF8.GetBytes("ownerPassword"));
PdfStamper pdfStamper = null;
//   pdfReader.Permissions = 1;
pdfStamper = new PdfStamper(pdfReader, pdfOutputFile);
AcroFields testForm = pdfStamper.AcroFields;

PdfContentByte pdfPageContents = pdfStamper.GetUnderContent(index + 1);
string[] formattext = printTxt.Split(new char[] { '\n' });
float lhight = 0;
float abxt = abx;

printTxt= "Hello word";

ft = new FormattedText(printTxt, Color.Black, "Arial", EncodingType.Winansi, true, 9);
Bitmap b = new Bitmap(1, 1);
Graphics graphics = Graphics.FromImage(b);
Font f = new Font("Arial", 9);

pdfPageContents.BeginText();

BaseFont baseFont = BaseFont.CreateFont(BaseFont.HELVETICA, "ASCII", false);
pdfPageContents.SetFontAndSize(baseFont,20); // 40 point font
pdfPageContents.SetRGBColorFill(0, 0, 0);
float textAngle = 0;

pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, printTxt, abx+3, (float)aby + 12 + lhight, textAngle);
pdfPageContents.EndText();

1 个答案:

答案 0 :(得分:1)

我用来在任何Pdf文件上写文本的方法是使用软件工具PDF Nitro Professional创建文本字段(您可以使用其他一些软件来创建这些字段)。完成后,您可以使用以下代码模式在这些字段上写入文本。

string pdfTemplate = filePath;
string newFile = outputFilePath;
PdfReader PDFWriter = new PdfReader(pdfTemplate);
PdfStamper pdfStampDocument = new PdfStamper(PDFWriter, new FileStream(newFile, FileMode.Create));
AcroFields pdfFormFields = pdfStampDocument.AcroFields;
//For Text field
pdfFormFields.SetField("txtTextFieldName", "First Text");
//For Check Box Field 
pdfFormFields.SetField("chkSomeCheckBox", "Yes");
PDFWriter.Close();
pdfStampDocument.Close();

希望它有所帮助。