0
votes

I'm very new to using iTextSharp to generate a pdf. I have the following code that places text from my form to the pdf output. I am using a Phrase & ColumnText to position the text from a particular textbox onto my pdf output. I've tied a variable as well as the text property of the textbox as the Phrase string, but it places two sets of the same text on top of each other(screenshot). enter image description here

string oldFile = Path.GetTempPath() + "invoice.pdf";
string newFile = Path.GetTempPath() + "NewInvoice.pdf";
PdfReader reader = new PdfReader(oldFile);
iTextSharp.text.Rectangle size = reader.GetPageSize(1);
Document doc = new Document(size);
FileStream fs = new FileStream(newFile, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
PdfWriter writer = PdfWriter.GetInstance(doc, fs);
doc.Open();
PdfContentByte cb = writer.DirectContent;
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, true);
cb.SetColorFill(BaseColor.BLACK);
cb.SetFontAndSize(bf, 12);
cb.BeginText();
cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, invoiceDate, 480, 603, 0);
cb.EndText();
PdfImportedPage page = writer.GetImportedPage(reader, 1);
cb.AddTemplate(page, 0, 0);

ColumnText ct = new ColumnText(cb);
Phrase phrase = new Phrase(textBox1.Text);
ct.SetSimpleColumn(phrase, 65, 375, 540, 300, 16, Element.ALIGN_LEFT);
ct.Go();
doc.Close();
fs.Close();
writer.Close();
reader.Close();
Process.Start(newFile);

If I assign a string (string whatever = "some text here...";) and place this in the Phrase string(..new Phrase(whatever); it works fine.

1

1 Answers

0
votes

Let me start by saying that I'm the original developer of iText.

I hope you'll believe me when I say you should use a PdfReader/PdfStamper combination instead of a Document/PdfWriter combination. This is documented in chapter 6 of my book. You may not see any difference on the outside, but the PDF feel be so much better on the inside.

It's kind of strange that you're adding text at absolute positions. Wouldn't it be better to use a template that has some AcroForm fields on the locations where text is needed? Your code will be so much easier to maintain.

I also see that you're using HELVETICA as font with the parameter for embedding equal to true. Surely you know that the embedded parameter will be ignored for HELVETICA which is one of the Standard Type 1 fonts.

Finally for your question: I don't think your code is adding the phrase twice. I think you've been experimenting and that you're adding a new phrase over a phrase that already exists in the original file "invoice.pdf". If you're 100% that this isn't the case, then you should share your PDF so that I (or somebody else at iText) can inspect it.