itext7

Modify Existing PDF With iText7


I'm trying to change the font of all the text-fields in an existing PDF file using iText7 and c#. In all the examples I've seen a PdfDocument object is created that has a "source" and "destination file". Below is my code to change the fonts.


string pdfFileSrc = @"C:\UnsecurePDF\3161_Dec2023.pdf";
string pdfFileDest = @"C:\UnsecurePDF\3161_Dec2023-3.pdf";                      
float fontSize = 8.00f; 
PdfFont fontTimesRoman = PdfFontFactory.CreateFont(iText.IO.Font.Constants.StandardFonts.TIMES_ROMAN);

 PdfDocument pdfDocument = new PdfDocument(new PdfReader(pdfFileSrc), new PdfWriter(pdfFileDest));
 PdfAcroForm acroForm = PdfAcroForm.GetAcroForm(pdfDocument, false); 
 var fields = acroForm.GetAllFormFields();

 foreach (var field in fields)
 {
     try
     {
         field.Value.SetFont(fontTimesRoman);
         field.Value.SetFontSize(fontSize);
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
     }

 }
 pdfDocument.Close();

I've successfully changed the font values via code, and the new values are in the destination PDF file. My question is, is there a way to simply modify the existing PDF file ( the source pdf file) without having to create an additional "destination" PDF file?


Solution

  • My question is, is there a way to simply modify the existing PDF file ( the source pdf file) without having to create an additional "destination" PDF file?

    iText does not work with both the PdfReader and the PdfWriter of a PdfDocument pointing to the same file.

    What you can do, though, is buffering the incoming or outgoing file in memory and then write the result to the same file as you had read from.

    I.e. you either first read the existing file into e.g. a MemoryStream and then open the PdfReader from that stream and point the PdfWriter to the original file; or you open the PdfReader from the file and point the PdfWriter to a MemoryStream, and after closing the PdfDocument store the stream contents to the file.