0

以下のコードを使用して、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();
4

1 に答える 1

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();

それが役に立てば幸い。

于 2012-04-10T06:40:34.627 に答える