Showing posts with label pdf. Show all posts
Showing posts with label pdf. Show all posts

Thursday, September 07, 2017

Merge and Paginate PDF files using iText 5

In this post we will see a way to merge multiple PDF files while adding page numbers at the bottom of each page in the format Page 1 of 10. The following steps give a brief description of the steps used to merge and add page number to the merged PDF.

Wednesday, September 06, 2017

Merge PDF files using iText 5

This is an example code for a simple PDF merge using iText 5. We use three InputStreams in a List as input and merged file is written to the file system.

Friday, December 08, 2006

PDF Generation with Big Faceless Report Generator

Big Faceless Report Generator is a commercial Java API for generating PDF files from XML input. The report generator is built on the Big Faceless Java PDF library. It has a very easy to use API, but the one thing that I like most about it is, for it is more than a bargain for the price you pay for it. It easily out performs the open source PDF generators (iText and XSL FOP) and also has a lot of intersting features.

Skip to Sample Code
  • HTML-style Tables - auto-sized nested tables with full control over padding, margins and borders
  • Support for CSS2 Style sheets
  • Create inline graphs and charts with XML, direct from the database
  • Includes a servlet and a servlet filter for simple generation of PDF's from XML or JSP pages.
  • Auto pagination of content with page headers and footers
  • Familiar HTML syntax - <a>, <ul>, <p>, <table>, <td> and so on - simpler and faster than FOP
  • Unicode support, Encryption, TrueType fonts, Barcodes and more
  • Load existing PDF documents as templates
  • Digitally sign documents
  • Create and edit interactive Forms, or "AcroForms"
The following is an example of how to use the Report generation library to create PDF files using an XML for input Data, and an XSL as a template. Follow these steps to implement the example
  1. Download Big Faceless Report generator from here. You only have to include the bforeport.jar file in your classpath.
  2. Create the input XML file as shown below:
    <?xml version="1.0" encoding="UTF-8"?>
    <Org>
    <Employee>
    <firstName>Asif</firstName>
    <lastName>Mandvi</lastName>
    <dateOfBirth>1/1/1900</dateOfBirth>
    </Employee>
    <Employee>
    <firstName>James</firstName>
    <lastName>Baker</lastName>
    <dateOfBirth>1/1/1900</dateOfBirth>
    </Employee>
    <Employee>
    <firstName>Jon</firstName>
    <lastName>Stewart</lastName>
    <dateOfBirth>1/1/1900</dateOfBirth>
    </Employee>
    <Employee>
    <firstName>Stephen</firstName>
    <lastName>Colbert</lastName>
    <dateOfBirth>1/1/1900</dateOfBirth>
    </Employee>
    <Employee>
    <firstName>Samantha</firstName>
    <lastName>Bee</lastName>
    <dateOfBirth>1/1/1900</dateOfBirth>
    </Employee>
    <Employee>
    <firstName>Jon</firstName>
    <lastName>Oliver</lastName>
    <dateOfBirth>1/1/1900</dateOfBirth>
    </Employee>
    </Org>
    test.xml
  3. Create the template for the PDF(XSL) as shown below.
    <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="yes" />
    <xsl:preserve-space elements="true" />
    <xsl:template match="Org">
    <pdf>
    <body>
    <table font-size="12pt" width="700px">
    <tr font-weight="bold">
    <td>First Name</td>
    <td>Last Name</td>
    <td>Date of Birth</td>
    </tr>
    <xsl:for-each select="/Org/Employee">
    <tr>
    <td>
    <xsl:value-of select="firstName" />
    </td>
    <td>
    <xsl:value-of select="lastName" />
    </td>
    <td>
    <xsl:value-of select="dateOfBirth" />
    </td>
    </tr>
    </xsl:for-each>
    </table>
    </body>
    </pdf>
    </xsl:template>
    </xsl:stylesheet>
    test.xsl
    This XSL file will be used to create the final XML file that will sent as input to the Report generator.
  4. Transform the XML to the format required by the report generator: The XML file cannot be used as input to the report generator directly. It has to be first transformed into the required format. That is reason for using the XSL.
    public class ConvertXML {
    public void renderReport() {
    try {
    TransformerFactory factory = TransformerFactory.newInstance();
    StreamSource stylesheet = new StreamSource(new FileInputStream("c:\\pdf\\test.xsl"));
    Transformer transformer = factory.newTransformer(stylesheet);
    Source src = new StreamSource(new FileInputStream("c:\\pdf\\test.xml"));
    Result res = new StreamResult(new FileOutputStream("c:\\pdf\\intermediate.xml"));
    transformer.transform(src, res);
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    }
    ConvertXML.java
  5. The following code can be used to generate the final PDF: The PDFGenerator first uses the ConvertXML to transform the input to the report generator input format (intermediate.xml), and then invokes the report generator.
    public class PDFGenerator {
    public void createPDF(String xmlfile, OutputStream out) {
    ReportParser parser;
    try {
    parser = ReportParser.getInstance();
    InputSource src = new InputSource(new FileInputStream(xmlfile));
    PDF pdf = (PDF) parser.parse(src);
    pdf.render(out);
    out.close();
    } catch (Exception e) {
    e.printStackTrace();
    }
    }

    public static void main(String args[]) {
    PDFGenerator gen = new PDFGenerator();
    OutputStream os = null;
    try {
    ConvertXML cx = new ConvertXML();
    cx.renderReport();
    os = new FileOutputStream("c:\\pdf\\test.pdf");
    } catch (FileNotFoundException e) {
    e.printStackTrace();
    }
    gen.createPDF("C:\\pdf\\intermediate.xml", os);
    }
    }
    PDFGenerator.java

Tuesday, November 28, 2006

Merge PDF files with iText

New posts with iText 5.5.12

Following are two new posts for PDF Merge with iText 5.5.12 The previous post described the use of iText to create a simple PDF. This post describes the use of iText to merge multiple PDF documents. The sample code here contains a method that will take the a list of PDF files as input, along with an OutputStream to which the merged PDF file will be written. This example also implements paging, i.e. along with merging the PDF files the merged PDF file also adds page numbers to the generated PDF file. The following is a brief description of the steps involved in merging PDF files using iText.
Skip to Sample code
  1. Create a PdfReader for each input PDF file
    PdfReader pdfReader = new PdfReader(pdf);
  2. Create a document object to represent the PDF.
    Document document = new Document();
  3. Create a PdfWriter for the target OutputStream
    PdfWriter writer = PdfWriter.getInstance(document, outputStream);
  4. Select a font with which the page numbers will be written
    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
  5. Create a a PdfContentByte object to hold the data of the merged PDF
    PdfContentByte cb = writer.getDirectContent();
  6. Add individual pages from the source to the target.
    document.newPage();
    pageOfCurrentReaderPDF++;
    currentPageNumber++;
    page1 = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
    cb.addTemplate(page1, 0, 0);
  7. Add page text at the bottom of the page
    cb.beginText();
    cb.setFontAndSize(bf, 9);
    cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "Page " + currentPageNumber + " of " + totalPages, 520, 5, 0);
    cb.endText();
The following is the complete source code merging PDF files.
public class MergePDF {
public static void main(String[] args) {
try {
List<InputStream> pdfs = new ArrayList<InputStream>();
pdfs.add(new FileInputStream("c:\\pdf\\2.pdf"));
pdfs.add(new FileInputStream("c:\\pdf\\3.pdf"));
OutputStream output = new FileOutputStream("c:\\pdf\\merge.pdf");
MergePDF.concatPDFs(pdfs, output, true);
} catch (Exception e) {
e.printStackTrace();
}
}

public static void concatPDFs(List<InputStream> streamOfPDFFiles, OutputStream outputStream, boolean paginate) {

Document document = new Document();
try {
List<InputStream> pdfs = streamOfPDFFiles;
List<PdfReader> readers = new ArrayList<PdfReader>();
int totalPages = 0;
Iterator<InputStream> iteratorPDFs = pdfs.iterator();

// Create Readers for the pdfs.
while (iteratorPDFs.hasNext()) {
InputStream pdf = iteratorPDFs.next();
PdfReader pdfReader = new PdfReader(pdf);
readers.add(pdfReader);
totalPages += pdfReader.getNumberOfPages();
}
// Create a writer for the outputstream
PdfWriter writer = PdfWriter.getInstance(document, outputStream);

document.open();
BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
PdfContentByte cb = writer.getDirectContent(); // Holds the PDF
// data

PdfImportedPage page;
int currentPageNumber = 0;
int pageOfCurrentReaderPDF = 0;
Iterator<PdfReader> iteratorPDFReader = readers.iterator();

// Loop through the PDF files and add to the output.
while (iteratorPDFReader.hasNext()) {
PdfReader pdfReader = iteratorPDFReader.next();

// Create a new page in the target for each source page.
while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
document.newPage();
pageOfCurrentReaderPDF++;
currentPageNumber++;
page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
cb.addTemplate(page, 0, 0);

// Code for pagination.
if (paginate) {
cb.beginText();
cb.setFontAndSize(bf, 9);
cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "" + currentPageNumber + " of " + totalPages, 520, 5, 0);
cb.endText();
}
}
pageOfCurrentReaderPDF = 0;
}
outputStream.flush();
document.close();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (document.isOpen())
document.close();
try {
if (outputStream != null)
outputStream.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}
MergePDF.java

PDF generation with iText

iText is a Java API for reading, writing, and editing PDF documents and PDF forms. The latest release (v1.4.7) adds support for AES encryption of documents, as well as better integration with Acrobat forms. The iText project's PDF library is perhaps the best-known open-source API to create, read, and edit PDF documents from Java. iText supports a rich set of PDF capabilities, such as the ability to select fonts, specify hyphenation, generate PDF in various page sizes, include tables and graphics in PDF documents, print page numbers, headers, and footers, use watermarks, and even supports the creation and reading of barcodes and document encryption. iText API also works with other report-oriented Java projects, such as JFree, allowing easy insertion of JFree reports or JFree charts in PDF documents.
The following example demonstrates how to create a simple PDF form using iText.
  1. Download the latest version of iText (v 1.4.7).
  2. The following piece of code can be used to generate a simple pdf with some text on it
    import java.io.FileOutputStream;
    import java.io.IOException;
    import com.lowagie.text.Document;
    import com.lowagie.text.DocumentException;
    import com.lowagie.text.Paragraph;
    import com.lowagie.text.pdf.PdfWriter;
    public class TestiText {
    public static void main(String[] args) {
    Document document = new Document();
    try {
    PdfWriter.getInstance(document, new FileOutputStream("c:\\test.pdf"));
    document.open();
    document.add(new Paragraph("iText Works :)"));
    } catch (DocumentException de) {
    de.printStackTrace();
    } catch (IOException ioe) {
    ioe.printStackTrace();
    }
    document.close();
    }
    }
    TestiText.java
  3. Paragraph is one of the page elements in iText a listing of the page elements can be found here.

Popular Posts