How to insert text into an existing PDF? [closed]

2

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

How can I do this using iTextSharp?

    
asked by anonymous 15.10.2017 / 22:01

1 answer

2

You can modify the document by using the DirectContent property of PdfWriter . So it modifies the content using ShowTextAligned of PdfContentByte . Font

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();
16.10.2017 / 23:23