I need to add another page in a pdf file created using below code. the next page should also use the same template placed at path:
HostingEnvironment.MapPath("~/Content/InvoiceTemplate/invoiceTemplate.pdf")
I am using itextsharp library to create documents. Below is the code used to generate pdf.
public static void WriteInTemplate(List<Models.Statement> statementList)
{
string invoiceNumber = statementList.FirstOrDefault().Invoice.ToString().Trim();
string month = null;
string day = null;
string year = null;
PdfReader pdfReader = new PdfReader(HostingEnvironment.MapPath("~/Content/InvoiceTemplate/invoiceTemplate.pdf"));
FileStream fileStream = new FileStream(HostingEnvironment.MapPath("~/Content/reports/" + invoiceNumber + ".pdf"), FileMode.Create);
PdfStamper pdfStamper = new PdfStamper(pdfReader, fileStream);
AcroFields pdfFields = pdfStamper.AcroFields;
pdfFields.SetField("BillToCompany", statementList.FirstOrDefault().BillToCompany.ToString().Trim().ToUpper());
pdfFields.SetField("BillToContact", statementList.FirstOrDefault().BillToContact.ToString().Trim().ToUpper());
pdfFields.SetField("CustomerId", statementList.FirstOrDefault().Customer_ID);
pdfFields.SetField("InvoiceNumber", statementList.FirstOrDefault().Invoice.ToString().Trim());
pdfFields.SetField("JobNumber", statementList.FirstOrDefault().JobNumber.ToString().Trim());
pdfFields.SetField("Caller", statementList.FirstOrDefault().Caller.ToString().Trim());
pdfStamper.FormFlattening = true; // generate a flat PDF
pdfStamper.Close();
pdfReader.Close();
}
You need to create a PDFDocument and then merge the files that you create into it. There is a very good example of this in this link: Merge PDFs using ITextSharp.
Related
I am trying to add a Cover Page PDF file to another PDF file. I am using CopyPagesTo method. CoverPageFilePath will go before any pages in the pdfDocumentFile. I then need to rewrite that new file to the same location. When I run the code and open the new pdf file I get an error about it being damaged.
public static void iText7MergePDF()
{
byte[] modifiedPdfInBytes = null;
string pdfCoverPageFilePath = #"PathtoCoverPage\Cover Page.pdf";
PdfDocument pdfDocumentCover = new PdfDocument(new iText.Kernel.Pdf.PdfReader(pdfCoverPageFilePath));
string pdfDocumentFile =#"PathtoFullDocument.pdf";
var buffer = File.ReadAllBytes(pdfDocumentFile);
using (var originalPdfStream = new MemoryStream(buffer))
using (var modifiedPdfStream = new MemoryStream())
{
var pdfReader = new iText.Kernel.Pdf.PdfReader(originalPdfStream);
var pdfDocument = new PdfDocument(pdfReader, new PdfWriter(modifiedPdfStream));
int numberOfPages = pdfDocumentCover.GetNumberOfPages();
pdfDocumentCover.CopyPagesTo(1, numberOfPages, pdfDocument);
modifiedPdfInBytes = modifiedPdfStream.ToArray();
pdfDocument.Close();
}
System.IO.File.WriteAllBytes(pdfGL, modifiedPdfInBytes);
}
Whenever you have some other type, like a StreamWriter, or here a PdfWriter writing to a Stream, it may not write all the data to the Stream immediately.
Here you Close the pdfDocument for all the data to be written to the MemoryStream.
ie this
modifiedPdfInBytes = modifiedPdfStream.ToArray();
pdfDocument.Close();
Should be
pdfDocument.Close();
modifiedPdfInBytes = modifiedPdfStream.ToArray();
I want to save a PDF file in a flatted mode. I have tried all the online solution but never works in my code.
I have a file generated with ITextSharp and Acrofields. When i try to set the option pdf.FormFlattening = true; it doesn't work for my solution.
The file is generated from an "Adobe Static PDF form" created with Adobe Livecycle Designer
This is my function:
using (var streamPdf = new MemoryStream())
{
PdfStamper pdf;
using (var pdfReader = new PdfReader(Application.StartupPath + PathToFile + Template))
using (pdf = new PdfStamper(pdfReader, streamPdf))
{
AcroFields pdfFormFields = pdf.AcroFields;
foreach (var field in fields)
{
pdfFormFields.SetField(field.FieldName, field.FieldValue.Trim());
}
}
foreach (var de in pdfReader.AcroFields.Fields)
{
pdfFormFields.SetFieldProperty(de.Key.ToString(),"setfflags",PdfFormField.FF_READ_ONLY,null);
}
pdf.FormFlattening = true;
pdf.AcroFields.GenerateAppearances = true;
pdf.Close();
_pdf = streamPdf.ToArray();
}
string filename = "name.pdf";
using (var fs = new FileStream(filename, FileMode.Create))
{
fs.Write(_pdf, 0, _pdf.Count());
fs.Close();
}
The file generated is a static PDF and i need to have a PDF without Fields.
Thanks to all
My task is to merge multiple pdf to single pdf and I can achieve the merger pdf but I am facing issue in the internal links (named destination) are missed up from second pdf where as its working in first pdf. My issues are similiar to the below post.
Pdf Merge Issue in ItextSharp (After Merging Pdfs don't retain their Values)
But I did not achieve this.
My code are below.
class Program
{
static void Main(string[] args)
{
Document document = new Document();
string[] fileNames = #"D:\PDF_Protect\ToMerge\Test\pdf1.pdf;D:\PDF_Protect\ToMerge\Test\pdf2.pdf;D:\PDF_Protect\ToMerge\Test\pdf3.pdf;".Split(';');
string outFile = #"D:\PDF_Protect\ToMerge\output\merged.pdf";
//merge one
PdfCopy pdf = new PdfCopy(document, new FileStream(outFile, FileMode.Create));
document.Open();
foreach (string fileName in fileNames)
{
PdfReader reader = new PdfReader(fileName);
reader.ConsolidateNamedDestinations();
var pdfDestination = new PdfDestination(PdfDestination.FIT);
//var pdfAction = PdfAction.GotoLocalPage(1, pdfDestination, pdf);
//pdf.SetOpenAction(pdfAction);
pdf.AddDocument(reader);
reader.Close();
}
document.Close();
}
}
Kindly guide me how to regenerate the links working throughout the merged pdf.
I have created one pdf file that i want to use as template page (contain header and border), so when i add new page to existing pdf it automatically set header and border to newly added page.
I am using ITextSharp PDF library.
I have try using PdfImportedPage as below but it's not working:
PdfReader templateFile;
templateFile = new PdfReader("D:\\templatefile.pdf");
PdfImportedPage template_page;
var fileStream1 = new FileStream("D:\\temp.pdf", FileMode.Create, FileAccess.Write);
var stamper1 = new PdfStamper(templateFile, fileStream1);
template_page = stamper1.GetImportedPage(templateFile, 1);
// now i want to add this template_page to existing pdf at specific position
//this is the file(existingpdf.pdf) in which i want to add template_page create above using stamper
var bytes = File.ReadAllBytes("D:\\existingpdf.pdf");
var reader = new PdfReader(bytes);
var numberofPages = reader.NumberOfPages;
var fileStream = new FileStream("D:\\result.pdf", FileMode.Create, FileAccess.Write);
//stamper of result pdf
var stamper = new PdfStamper(reader, fileStream);
stamper.InsertPage(numberofPages + 1, templateFile.GetPageSize(1));
//below code i have tried to add template but its not working in result pdf
stamper.GetUnderContent(2).AddTemplate(template_page, 0, 0);
stamper.Close();
I'm struggling to insert images on a multi-page PDF.
To create several pages I'm using PdfConcatenate, and it works. I get to add pages of my template perfectly. The problem starts when I try to add images. It just doesn't load them.
Here's the code that works to add images:
string pdfTemplate = #"Tools\template.pdf";
string targetPdfPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), fileName + ".pdf");
FileStream output = new FileStream(targetPdfPath, FileMode.Create);
PdfConcatenate pdfConcatenate = new PdfConcatenate(output);
PdfReader pdfReader = new PdfReader(pdfTemplate);
MemoryStream memoryStream = getMemoryStream(output);
PdfStamper pdfStamper = new PdfStamper(pdfReader, output);
int cardIndex = 1;
foreach (Registry reg in registries)
{
setFields(reg, pdfStamper, cardIndex);
if (cardIndex == 4)
{
pdfConcatenate.AddPages(pdfReader);
pdfReader = new PdfReader(pdfTemplate);
pdfStamper = new PdfStamper(pdfReader, output);
cardIndex = 1;
}
else
{
cardIndex++;
}
}
//if (cardIndex != 1)
// pdfConcatenate.AddPages(pdfReader);
//make the form no longer editable
pdfStamper.FormFlattening = true;
pdfStamper.Close();
pdfReader.Close();
//pdfConcatenate.Close();
If use MemoryStream for PdfStamper and uncomment these lines:
//if (cardIndex != 1)
// pdfConcatenate.AddPages(pdfReader);
//pdfConcatenate.Close();
I get it to add pages, but without images.
Any idea of what is wrong?
SOLUTION: (Thanks to #mkl)
string pdfTemplate = #"Tools\template.pdf";
string targetPdfPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), fileName + ".pdf");
FileStream output = new FileStream(targetPdfPath, FileMode.Create);
PdfConcatenate pdfConcatenate = new PdfConcatenate(output);
PdfReader pdfReader = new PdfReader(pdfTemplate);
MemoryStream memoryStream = new MemoryStream();
PdfStamper pdfStamper = new PdfStamper(pdfReader, memoryStream);
int cardIndex = 1;
foreach (Registry reg in registries)
{
setFields(reg, pdfStamper, cardIndex);
if (cardIndex == 4)
{
pdfStamper.FormFlattening = true;
pdfStamper.Close();
PdfReader tempReader = new PdfReader(memoryStream.ToArray());
pdfConcatenate.AddPages(tempReader);
memoryStream = new MemoryStream();
pdfReader = new PdfReader(pdfTemplate);
pdfStamper = new PdfStamper(pdfReader, memoryStream);
cardIndex = 1;
}
else
{
cardIndex++;
}
}
if (cardIndex != 1)
{
pdfStamper.FormFlattening = true;
pdfStamper.Close();
PdfReader tempReader = new PdfReader(memoryStream.ToArray());
pdfConcatenate.AddPages(tempReader);
tempReader.Close();
}
pdfStamper.Close();
pdfReader.Close();
pdfConcatenate.Close();
The problem most likely is some misconception on how PdfStamperworks. You seem to think it somehow manipulates the data in the PdfReader it stamps, and also pages exported from that reader beforehand. This is not the case, a PdfStamper generates a new PDF file (in its output stream) based on the data in the reader but the contents of the reader itself are not updated to also reflect all the changes (the PdfReader object may be touched in the process, though, and not be reusable afterwards). So...
As already mentioned in the comment, you have the PdfConcatenate and an unknown number of PdfStamper instances all writing the same `FileStream' output. As each of these objects creates an independant PDF, you are lucky if one of then wins because then you'll get at least a proper PDF as output. Otherwise you either get some exception or garbage consisting of multiple intermingled PDFs. Thus, make only PdfConcatenate target your output file.
If your actual intent is to repeatedly fill the template fields with the content of 4 cards each time and combine the results, you should not add the pages from the PdfReader of the template to the PdfConcatenate --- the pages in that reader are not filled in! --- but instead have the PdfStamper output to a MemoryStream, fill its fields, flatten its form, close it, open its output in a new PdfReader, and add all the pages in that reader to the PdfConcatenate.
I don't dare to put that into code as I'm predominantly using Java and writing down untested C# code most likely would include multiple errors... ;)
PS: Currently you count on all the PdfReader instances you open to be implicitly closed somewhere. While that is true currently, recent check-ins in the iText SVN repository seem to indicate that these implicit close calls are removed from the code. Thus, please also start explicitly closing PdfReader instances you dont't use anymore. Otherwise you will soon have to deal with memory leaks due to readers closing much too late..