Reputation: 617
currently writing a small C# program with PDFSharp but I have a problem that I can't seem to figure out. The program is used to load in a pre-made PDF with a number of forms present, I want to read the original PDF in, duplicate it's contents into a new PDF and then fill out the forms in the new PDF. So far I have the following code:
inPDF = PdfReader.Open(sourceFile, PdfDocumentOpenMode.Import);
outPDF = new PdfDocument();
for (int idx = 0; idx < inPDF.PageCount; ++idx)
{
outPDF.AddPage(inPDF.Pages[idx]);
}
However the new PDF does not have any of the forms present in the original, how can I duplicate the contents (including forms) of the original PDF?
Thanks, RBrNx
Upvotes: 4
Views: 476
Reputation: 1
Came across this recently as I had the same issue. It seems like form fields are considered PDF annotations, so just set the second parameter:
outPDF.AddPage(inPDF.Pages[idx], AnnotationCopyingType.DeepCopy)
I'm not sure if DeepCopy
is necessary versus ShallowCopy
, but it probably won't hurt.
Upvotes: 0
Reputation: 34
I feel I am a bit late, but you almost got it back in those days!
You have 2 options, using AddPage
or InsertPage
. The main problem I encountered is that the Encoding was mandatory (I am not sure if it was only me) but here you have the code:
using System.Text;
using System.Windows;
using PdfSharp.Pdf;
using PdfSharp.Pdf.IO;
Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
sourceFile = "YourDirectory/YourOriginalDocument.pdf";
finalFile = "YourDirectory/YourFinalDocument.pdf";
var outPDF = new PdfDocument();
var inPDF = PdfReader.Open(sourceFile, PdfDocumentOpenMode.Import);
for (int idx = 0; idx < inPDF.PageCount; ++idx)
{
//outPDF.InsertPage(idx, inPDF.Pages[idx]); // if you prefer....
outPDF.AddPage(inPDF.Pages[idx]);
}
// Save
outPDF.Save(finalFile);
Notice that you forgot to save the pdf (using method Save
), but as I told you before, you were really close!
Upvotes: 0