PDFsharp & MigraDoc Foundation

PDFsharp - A .NET library for processing PDF & MigraDoc Foundation - Creating documents on the fly
It is currently Wed Feb 05, 2025 5:53 am

All times are UTC


Forum rules


Please read this before posting on this forum: Forum Rules



Post new topic Reply to topic  [ 2 posts ] 
Author Message
PostPosted: Wed Jan 15, 2025 2:00 pm 
Offline

Joined: Wed Jan 15, 2025 1:44 pm
Posts: 2
Hi

I´m trying to load a pdf containing a form with fields , fill out the form and save the new file.
This works fine but now i want to take this to the next level and use the template in a loop to create multiple pages with filled values.

create empty document
Load template
Loop thru names
Fill out form-field with the name
Add the filled templates page to the empty document
Save the document , now with multiple pages and all names filled out.

I can sort of get it to work but when i look at the saved document the fields are the same or not filled out depending on pdf-viewer
In chrome all pages has the same text and in firefox it works but when makeing field readonly its empty

Code:
string templatePath = @"c:\temp\code_eng.pdf";
string outputPath = @"c:\temp\filled_form.pdf";

// Create a new document for the output
PdfDocument outputDocument = new PdfDocument();

// Example data for filling out the forms
var data = new[]
{
         new { Name = "Alice" },
         new { Name = "Sample" },
         new { Name = "Charlie"}
      };

foreach (var item in data)
{
   outputDocument.AddPage(GenerateDocumentPdf(item.Name));


}
outputDocument.Save(outputPath);

PdfPage? GenerateDocumentPdf(string name)
{

   using (MemoryStream _Stream = new MemoryStream())
   {
      //Load template
      PdfDocument template = PdfReader.Open(templatePath, PdfDocumentOpenMode.Modify);

      var fields = template.AcroForm.Fields;

      // Fill out individual fields
      if (fields["Name"] is PdfTextField nameField)
      {
         nameField.Value = new PdfString(name);
         //nameField.ReadOnly = true;
      }
            
      template.Save(_Stream);

      return PdfReader.Open(_Stream, PdfDocumentOpenMode.Import).Pages[0];
   }
}


Top
 Profile  
Reply with quote  
PostPosted: Thu Jan 16, 2025 10:40 am 
Offline

Joined: Wed Jan 15, 2025 1:44 pm
Posts: 2
Hi

Got this to work, sort of :-)

Using a pdf-form as template for multiple pages do not really work.
Loading template , fill out form fields and then add the page to a new document works for one page. If you have multiple pages all pages get the same form values.
Solution for this is to rename the form field names to unique names before adding the page to the new document.

Using flatten should solve this by just removing fileds and add it as text but i do not.

So renaming fields and using flatten() make the pages show the right values when you view this in chrome, but when i view it in firefox or acrobat the text is blank. Same this if you make the field read only.
If i do not make Flatten or readonly the text is shown , but then the filelds are blue and editable.

Doing the same thing without form fields and just adding xGraphics works fine.

Including code if someone has the same problem. May not be the best way to do this. (the reason for the byte[] is that this will come from a db in the future.)

Code:
string inputFile = @"c:\temp\code_se_2.pdf";
string outputFile = @"c:\temp\filled_form.pdf";

byte[] templateBytes = File.ReadAllBytes(inputFile);

PdfSharp.Pdf.PdfDocument outputDocument2 = new PdfSharp.Pdf.PdfDocument();

AddPage(templateBytes, "User1", ref outputDocument2);
AddPage(templateBytes, "User2", ref outputDocument2);

outputDocument2.Save(outputFile);


void AddPage(byte[] templateByte, string name, ref PdfSharp.Pdf.PdfDocument d)
{
   var _tmp = GeneratePdf(templateByte, name);

   using (MemoryStream inputStream2 = new MemoryStream(_tmp))
   {
      PdfSharp.Pdf.PdfDocument document2 = PdfReader.Open(inputStream2, PdfDocumentOpenMode.Import);

      d.AddPage(document2.Pages[0]);

      document2 = null;
   }
}

byte[] GeneratePdf(byte[] templateByte, string name)
{
   byte[] _tmp =[];

   using (MemoryStream inputStream = new MemoryStream(templateByte))
   {
      PdfSharp.Pdf.PdfDocument document = PdfReader.Open(inputStream, PdfDocumentOpenMode.Modify);
//      PdfPage page = document.Pages[0];
//      XGraphics gfx = XGraphics.FromPdfPage(page);
//
//      // Define the font to use for drawing text
//      XFont fontLarge = new XFont("Courie", 16, XFontStyleEx.Bold);
//      XFont fontMedium = new XFont("Courie", 12);
//      XFont fontSmall = new XFont("Arial", 9);
//
//      int startLine = 105;
//      string[] text = $"{name}".Split('\n');
//
//      //
//      foreach (var t in text)
//      {
//         gfx.DrawString(t, fontMedium, XBrushes.Black, new XPoint(320, startLine += 14));
//      }
            var uniqueIndex = Guid.NewGuid();
            var fields = document.AcroForm.Fields;
            var fieldNames = fields.Names;
      
            for (int idx = 0; idx < fieldNames.Length; ++idx)
            {
               var fieldName = fieldNames[idx];
               document.AcroForm.Fields[idx].Elements.SetString("/T", $"{fieldName}_{uniqueIndex}");
            }
      
      
            document.AcroForm.Fields[$"Name_{uniqueIndex}"].Value = new PdfString($"{name}");
      //document.AcroForm.Fields[$"Name_{uniqueIndex}"].ReadOnly = true;

      document.Flatten();
      using (MemoryStream outputStream = new MemoryStream())
      {
         document.Save(outputStream);

         _tmp = outputStream.ToArray();
      }

      document.Close();
   }

   return _tmp;
}


Top
 Profile  
Reply with quote  
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 2 posts ] 

All times are UTC


Who is online

Users browsing this forum: No registered users and 14 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Search for:
Jump to:  
Privacy Policy, Data Protection Declaration, Impressum
Powered by phpBB® Forum Software © phpBB Group