How to insert text into an existing PDF?

Asked

Viewed 1,225 times

2

I have a contract template ready and with nothing filled out. I need to fill out the requested information with what will be typed in some TextBox.

How can I do this using iTextSharp?

  • If any answer solved your problem may accept it :-)

1 answer

1


You can modify the document using the property DirectContent of PdfWriter. Thus modifies the content using ShowTextAligned of PdfContentByte. Source

string oldFile = "oldFile.pdf";
string newFile = "newFile.pdf";

// cria o PdfReader
PdfReader reader = new PdfReader(oldFile);
Rectangle size = reader.GetPageSizeWithRotation(1);
Document document = new Document(size);

// cria o PdfWriter
FileStream fs = new FileStream(newFile, FileMode.Create, FileAccess.Write);
PdfWriter writer = PdfWriter.GetInstance(document, fs);
document.Open();

// o conteúdo do PDF
PdfContentByte cb = writer.DirectContent;

// as propriedades da fonte
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252,BaseFont.NOT_EMBEDDED);
cb.SetColorFill(BaseColor.DARK_GRAY);
cb.SetFontAndSize(bf, 8);

// escrever o texto no PDF
cb.BeginText();
string text = "Meu texto!";
// o alinhamento e as coordenadas de onde o texto ficará
cb.ShowTextAligned(1, text, 520, 640, 0);
cb.EndText();
cb.BeginText();

// mais texto a adicionar o PDF
text = "Mais texto!";
// novamente, o alinhamento e a posição
cb.ShowTextAligned(2, text, 100, 200, 0);
cb.EndText();

// cria um novo documento PDF
PdfImportedPage page = writer.GetImportedPage(reader, 1);
cb.AddTemplate(page, 0, 0);

// fecha o stream
document.Close();
fs.Close();
writer.Close();
reader.Close();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.