How to merge two pdf files with layers using itextsharp in C#, I tried but losing layers
// step 1: creation of a document-object
Document document = new Document();
// step 2: we create a writer that listens to the document
PdfCopy writer = new PdfCopy(document, new FileStream(outPutFilePath, FileMode.Create));
if(writer == null)
{
return;
}
// step 3: we open the document
document.Open();
foreach(string fileName in filesPath)
{
// we create a reader for a certain document
PdfReader reader = new PdfReader(fileName);
reader.ConsolidateNamedDestinations();
// step 4: we add content
for(int i = 1; i <= reader.NumberOfPages; i++)
{
PdfImportedPage page = writer.GetImportedPage(reader, i);
page.ContentTagged = true;
writer.AddPage(page);
}
PRAcroForm form = reader.AcroForm;
if(form != null)
{
// writer.CopyDocumentFields(reader);
}
reader.Close();
}
// step 5: we close the document and writer
writer.Close();
document.Close();
I am trying to merge two pdf files (file1.pdf and file2.pdf) into a single file file3.pdf. One of the source files, file2.pdf has few attachments.
Using PdfCopyFields addDocument method does not include the attachments in the source pdf files to the destination pdf file. How do I achieve this?
Extracting the document level attachments from source files using PdfDictionary and adding them to the destination file using PdfWriter addFileAttachment method works.
Can you please let me know if there is any other efficient method to include the attachments from source pdf files to be included in destination pdf file after merging?
This is the sample code that I am using to replicate the scenario.
public class TestItext
{
public String[] attachments;
public TestItext()
{
attachments = new String[2];
}
public static void main(String[] args)
{
try
{
TestItext obj = new TestItext();
obj.extractDocLevelAttachments("C:\\source.pdf");
obj.addAttachments("C:\\source.pdf","C:\\temp\\dest.pdf");
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void extractDocLevelAttachments(String filename) throws IOException
{
PdfReader reader = new PdfReader(filename);
PdfDictionary root = reader.getCatalog();
PdfDictionary documentnames = root.getAsDict(PdfName.NAMES);
PdfDictionary embeddedfiles = documentnames.getAsDict(PdfName.EMBEDDEDFILES);
PdfArray filespecs = embeddedfiles.getAsArray(PdfName.NAMES);
PdfDictionary filespec;
PdfDictionary refs;
FileOutputStream fos;
PRStream stream;
int count = 0;
for (int i = 0; i < filespecs.size(); ) {
filespecs.getAsString(i++);
filespec = filespecs.getAsDict(i++);
refs = filespec.getAsDict(PdfName.EF);
for (Object key : refs.getKeys()) {
fos = new FileOutputStream(String.format("C:\\temp\\"+ filespec.getAsString((PdfName)key).toString()));
attachments[count++] = String.format("C:\\temp\\"+ filespec.getAsString((PdfName)key).toString());
stream = (PRStream) PdfReader.getPdfObject(refs.getAsIndirectObject((PdfName)key));
fos.write(PdfReader.getStreamBytes(stream));
fos.flush();
fos.close();
}
}
reader.close();
}
public void addAttachments(String src, String dest) throws IOException, DocumentException
{
PdfReader reader = new PdfReader(src);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
for (int i = 0; i < attachments.length; i++) {
addAttachment(stamper.getWriter(), new File(attachments[i]));
}
stamper.close();
}
protected void addAttachment(PdfWriter writer, File src) throws IOException {
PdfFileSpecification fs =
PdfFileSpecification.fileEmbedded(writer, src.getAbsolutePath(), src.getName(), null);
writer.addFileAttachment(src.getName().substring(0, src.getName().indexOf('.')), fs);
}
}
I am trying to download and merges multiple pdf files by using ITextSharp.
It used to working before but I being got an "Content can not be added to a PdfImportedPage." error message on the line:
importedPage = writer.GetImportedPage(reader, currentPageIndex);
The full code is below, any help will be very appreciated.
private string MergeDocuments(IList<string> fileUrls, string fileName)
{
var reportFolder = this.ReportFolder + "\\";
using (MemoryStream output = new MemoryStream())
{
Document document = new Document();
try
{
// Initialize pdf writer
PdfWriter writer = PdfWriter.GetInstance(document, output);
// Open document to write
document.Open();
PdfContentByte content = writer.DirectContent;
PdfImportedPage importedPage;
// Iterate through all pdf documents
foreach (var url in fileUrls)
{
// Create pdf reader
using (PdfReader reader = new PdfReader(new Uri(url)))
{
int numberOfPages = reader.NumberOfPages;
// Iterate through all pages
for (int currentPageIndex = 1; currentPageIndex <= numberOfPages; currentPageIndex++)
{
// Determine page size for the current page
document.SetPageSize( reader.GetPageSizeWithRotation(currentPageIndex) );
// Create page
document.NewPage();
importedPage = writer.GetImportedPage(reader, currentPageIndex);
content.AddTemplate(importedPage, 1f, 0, 0, 1f, 0, 0);
}
}
}
}
catch (Exception exception)
{
throw new Exception("Error occured", exception);
}
File.WriteAllBytes(reportFolder + fileName + ".pdf", output.GetBuffer());
}
return "Reports/" + fileName + ".pdf";
}
When I try the following code, I get a null pointer exception in the addDocument() method:
using (MemoryStream output = new MemoryStream()) {
Document document = new Document();
document.Open();
PdfCopy copy = new PdfSmartCopy(document, output);
foreach (var url in fileUrls) {
using (WebClient client = new WebClient()) {
var byteArray = client.DownloadData(url);
PdfReader reader = new PdfReader(byteArray);
copy.AddDocument(reader);
reader.Close();
}
}
}
I found the problem, the document object should be closed before writing memory stream to file.
Just added document.Close() as below.
document.Close();
File.WriteAllBytes(reportFolder + fileName + ".pdf", output.GetBuffer());
Following is a code snippet creating a pdf file where pages could be rotated in the resulting file. This works fine for most pdf files. But one particualr pdf file of version 1.6 the page is already rotated by 180, on applying further rotation to it e.g. 90 degress and saving the file causes it to get corrupted. Infact even if you don't rotate the file and simply write it out to another file using iText the file the resulting pdf is corrupted and displays an out of memory exception when opened in Adobe reader.
Why would that happen? Am I missing some sort of compression in the file.
private String createPdfFileWithoutForms(final EditStateData[] editStateData, final String directory)
throws EditingException {
Long startTime = System.currentTimeMillis();
File pdfFileToReturn = new File(directory + File.separator + UidGenerator.generate() + ".pdf");
com.lowagie.text.Document document = null;
FileOutputStream outputStream = null;
PdfCopy pdfCopy = null;
PdfReader reader = null;
PdfDictionary pageDict = null;
int rotationAngle = 0;
Map<Integer, Integer> rotationQuadrants = null;
try {
document = new com.lowagie.text.Document();
outputStream = new FileOutputStream(pdfFileToReturn);
pdfCopy = new PdfCopy(document, outputStream);
pdfCopy.setFullCompression();
pdfCopy.setCompressionLevel(9);
document.open();
for (EditStateData state : editStateData) {
try {
reader = new PdfReader(state.getFileName());
reader.selectPages(state.getPages());
rotationQuadrants = state.getRotationQuadrants();
for (int i = 1; i <= reader.getNumberOfPages(); i++) {
// Rotation quadrant key is the source page number
if (rotationQuadrants.containsKey(state.getPages().get(i - 1))) {
rotationAngle = reader.getPageRotation(i);
pageDict = reader.getPageN(i);
pageDict.put(PdfName.ROTATE,
new PdfNumber((rotationAngle
+ rotationQuadrants.get(state.getPages().get(i - 1))) % 360));
}
document.setPageSize(reader.getPageSizeWithRotation(i));
document.newPage();
// import the page from source pdf
PdfImportedPage page = pdfCopy.getImportedPage(reader, i);
// add the page to the destination pdf
pdfCopy.addPage(page);
}
} catch (final IOException e) {
LOGGER.error(e.getMessage(), e);
throw new EditingException(e.getMessage(), e);
} finally {
if (reader != null) {
reader.close();
}
}
}
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
throw new EditingException(e.getMessage(), e);
} finally {
if (document != null) {
document.close();
}
if (pdfCopy != null) {
pdfCopy.close();
}
IoUtils.closeQuietly(outputStream);
}
LOGGER.debug("Combining " + editStateData.length + " pdf files took "
+ ((System.currentTimeMillis() - startTime) / 1000) + " msecs");
return pdfFileToReturn.getAbsolutePath();
}
I am creating a PDF using iText. I want to insert blank lines between paragraphs and tables.
How can I achieve this?
You can trigger a newline by inserting Chunk.NEWLINE into your document. Here's an example.
public static void main(String args[]) {
try {
// create a new document
Document document = new Document( PageSize.A4, 20, 20, 20, 20 );
PdfWriter.getInstance( document, new FileOutputStream( "HelloWorld.pdf" ) );
document.open();
document.add( new Paragraph( "Hello, World!" ) );
document.add( new Paragraph( "Hello, World!" ) );
// add a couple of blank lines
document.add( Chunk.NEWLINE );
document.add( Chunk.NEWLINE );
// add one more line with text
document.add( new Paragraph( "Hello, World!" ) );
document.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
Below is a screen shot showing part of the PDF that the code above produces.
And to insert blank line between tables you can use these both methods
table.setSpacingBefore();
table.setSpacingAfter();
You can use "\n" in Paragraph
document.add(new Paragraph("\n\n"));
You can try a blank phrase:
document.add(new Phrase("\n"));
You can add Blank Line throw PdfContentByte class in itextPdf. As shown below:
package com.pdf.test;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
public class Ranvijay {
public static final String RESULT = "d:/printReport.pdf";
public void createPdf(String filename) throws Exception {
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document,
new FileOutputStream(filename));
document.open();
Font bold = new Font(Font.FontFamily.HELVETICA, 8f, Font.BOLD);
Font normal = new Font(Font.FontFamily.HELVETICA, 8f, Font.NORMAL);
PdfPTable tabletmp = new PdfPTable(1);
tabletmp.getDefaultCell().setBorder(Rectangle.NO_BORDER);
tabletmp.setWidthPercentage(100);
PdfPTable table = new PdfPTable(2);
float[] colWidths = { 45, 55 };
table.setWidths(colWidths);
String imageUrl = "http://ssl.gstatic.com/s2/oz/images/logo/2x/googleplus_color_33-99ce54a16a32f6edc61a3e709eb61d31.png";
Image image2 = Image.getInstance(new URL(imageUrl));
image2.setWidthPercentage(60);
table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
table.getDefaultCell().setVerticalAlignment(Element.ALIGN_TOP);
PdfPCell cell = new PdfPCell();
cell.setBorder(Rectangle.NO_BORDER);
cell.addElement(image2);
table.addCell(cell);
String email = "ranvijay9286#gmail.com";
String collectionDate = "09/09/09";
Chunk chunk1 = new Chunk("Date: ", normal);
Phrase ph1 = new Phrase(chunk1);
Chunk chunk2 = new Chunk(collectionDate, bold);
Phrase ph2 = new Phrase(chunk2);
Chunk chunk3 = new Chunk("\nEmail: ", normal);
Phrase ph3 = new Phrase(chunk3);
Chunk chunk4 = new Chunk(email, bold);
Phrase ph4 = new Phrase(chunk4);
Paragraph ph = new Paragraph();
ph.add(ph1);
ph.add(ph2);
ph.add(ph3);
ph.add(ph4);
table.addCell(ph);
tabletmp.addCell(table);
PdfContentByte canvas = writer.getDirectContent();
canvas.saveState();
canvas.setLineWidth((float) 10 / 10);
canvas.moveTo(40, 806 - (5 * 10));
canvas.lineTo(555, 806 - (5 * 10));
canvas.stroke();
document.add(tabletmp);
canvas.restoreState();
PdfPTable tabletmp1 = new PdfPTable(1);
tabletmp1.getDefaultCell().setBorder(Rectangle.NO_BORDER);
tabletmp1.setWidthPercentage(100);
document.add(tabletmp1);
document.close();
}
/**
* Main method.
*
* #param args
* no arguments needed
* #throws DocumentException
* #throws IOException
*/
public static void main(String[] args) throws Exception {
new Ranvijay().createPdf(RESULT);
System.out.println("Done Please check........");
}
}
document.add(new Paragraph(""))
It is ineffective above,must add a blank string, like this:
document.add(new Paragraph(" "));
You can add empty line ;
Paragraph p = new Paragraph();
// add one empty line
addEmptyLine(p, 1);
// add 3 empty line
addEmptyLine(p, 3);
private static void addEmptyLine(Paragraph paragraph, int number) {
for (int i = 0; i < number; i++) {
paragraph.add(new Paragraph(" "));
}
}
You can also use
document.add(new Paragraph());
document.add(new Paragraph());
before seperator if you are using either it is fine.
Instead of using:
document.add( Chunk.NEWLINE );
use this:
document.add(new Paragraph(""));
it makes small space
directly use
paragraph.add("\n");
to add an empty line.
I posted this in another question, but I find using tables with iTextSharp offers a great level of precision.
document.Add(BlankLineDoc(16));
public static PdfPTable BlankLineDoc(int height)
{
var table = new PdfPTable(1) {WidthPercentage = 100};
table = BlankLineTable(table, height);
return table;
}
public static PdfPTable BlankLineTable(PdfPTable table, int height, int border = Rectangle.NO_BORDER)
{
var cell = new PdfPCell(new Phrase(" "))
{
Border = border,
Colspan = table.NumberOfColumns,
FixedHeight = height
};
table.AddCell(cell);
return table;
}
BlankLineTable can be used directly when working with tables
I had to add blank lines after a table and I manage it adding many divs as I need it with a css style with padding-top set it up, like this. I've used a template engine (underscore) to loop through the number of lines I need to add.
<% var maxRow = 30; var pos = items.models.length; %>
<% for( pos; pos < maxRow; pos++ ){ %>
<div class="blankRow"></div>
<% }; %>
My css file:
.blankRow:{ padding-top: 15px;}