01. How to create a PDF file in Java

1 Introduction

In this quick article, we will focus based on the popular iText and PdfBox from scratch to create a PDF document libraries.

2. Maven relies

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.10</version>
</dependency>
<dependency>
    <groupId>org.apache.pdfbox</groupId>
    <artifactId>pdfbox</artifactId>
    <version>2.0.4</version>
</dependency>

The latest version can be found in the library here: iText and PDFBox .

If we want to encrypt the file, you need to add an additional dependency. Bounty Castle Provider at The . Package contains encryption algorithm, and the two libraries are required:

<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcprov-jdk15on</artifactId>
    <version>1.56</version>
</dependency>

The latest version can be found in the library here: at The Bounty Castle Provider .

3. Overview

iText and PdfBox are used to create / manipulate Java library pdf file. Although the final output of these libraries is the same, but they are slightly different mode of operation. Let's look at them.

4. Create Pdf in the IText

4.1 insert text in Pdf

Let's look at the new file with the "Hello World" text inserted pdf file of the way

Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream("iTextHelloWorld.pdf"));

document.open();
Font font = FontFactory.getFont(FontFactory.COURIER, 16, BaseColor.BLACK);
Chunk chunk = new Chunk("Hello World", font);

document.add(chunk);
document.close();

Based on the use iText library to create pdf is manipulated to achieve the object (in version 5.5.10, 45 of implementations) Elements in the Document interface.

You can be added to the document using the smallest element called Chunk, basically with an application font string.

Further, the Chunk may be used in combination with other elements (e.g., Paragraphs, Section, etc.), thereby forming a beautiful document.

4.2 Insert Picture

iText library provides an easy way to add images to a document. We just need to create an instance of Image and add it to the Document.

Path path = Paths.get(ClassLoader.getSystemResource("Java_logo.png").toURI());

Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream("iTextImageExample.pdf"));
document.open();
Image img = Image.getInstance(path.toAbsolutePath().toString());
document.add(img);

document.close();

Insert Table 4.3

When we want to add a table in the pdf file, you may experience problems. Fortunately, iText provides such functionality out of the box.

First of all, we need to create a PdfTable object and provides a number of columns to our table in the constructor. Now we can simply add a new cell by calling

Now, we can simply add a new cell by calling the method on the table addCell newly created object. As long as the definition of all the necessary cells, iText table row is created, which means that once a table created containing 3 to 8 wherein the cell is added, only 2 lines, each row contains three Cell.

Let's look at an example:

Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream("iTextTable.pdf"));

document.open();

PdfPTable table = new PdfPTable(3);
addTableHeader(table);
addRows(table);
addCustomRows(table);

document.add(table);
document.close();

We create a new table 3 has three rows. We will be seen as the first line of the table header, the background color and border width has been changed:

private void addTableHeader(PdfPTable table) {
    Stream.of("column header 1", "column header 2", "column header 3")
      .forEach(columnTitle -> {
        PdfPCell header = new PdfPCell();
        header.setBackgroundColor(BaseColor.LIGHT_GRAY);
        header.setBorderWidth(2);
        header.setPhrase(new Phrase(columnTitle));
        table.addCell(header);
    });
}

The second row will be composed of three cells, with text only, no additional formatting.

private void addRows(PdfPTable table) {
    table.addCell("row 1, col 1");
    table.addCell("row 1, col 2");
    table.addCell("row 1, col 3");
}

We can not only include text in a cell, it can also include images. Further, each cell may be formatted separately provided in the example below, we apply the horizontal and vertical alignment adjustments:

private void addCustomRows(PdfPTable table)
  throws URISyntaxException, BadElementException, IOException {
    Path path = Paths.get(ClassLoader.getSystemResource("Java_logo.png").toURI());
    Image img = Image.getInstance(path.toAbsolutePath().toString());
    img.scalePercent(10);

    PdfPCell imageCell = new PdfPCell(img);
    table.addCell(imageCell);

    PdfPCell horizontalAlignCell = new PdfPCell(new Phrase("row 2, col 2"));
    horizontalAlignCell.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(horizontalAlignCell);

    PdfPCell verticalAlignCell = new PdfPCell(new Phrase("row 2, col 3"));
    verticalAlignCell.setVerticalAlignment(Element.ALIGN_BOTTOM);
    table.addCell(verticalAlignCell);
}

File Encryption 4.4

In order to use iText library application privileges, we need to have created a pdf document. In our example, we will use previously generated iTextHelloWorld.pdf file.

After using PdfReader load a file, we need to create a PdfStamper, applied for other content metadata, such as file encryption:

PdfReader pdfReader = new PdfReader("HelloWorld.pdf");
PdfStamper pdfStamper
  = new PdfStamper(pdfReader, new FileOutputStream("encryptedPdf.pdf"));

pdfStamper.setEncryption(
  "userpass".getBytes(),
  ".getBytes(),
  0,
  PdfWriter.ENCRYPTION_AES_256
);

pdfStamper.close();

In our example, we use two passwords to files encrypted. User password ( "userpass") (where the user has only read-only permission can not be printed), as well as owner password ( "ownerpass") as a master key that allows users full access to pdf.

If we want to allow users to print pdf, instead of 0 (setEncryption third parameter), we can deliver:

PdfWriter.ALLOW_PRINTING

Of course, we can mix with different privileges, such as:

PdfWriter.ALLOW_PRINTING | PdfWriter.ALLOW_COPY

Remember to use iText set access permissions, we will also create a temporary pdf, should be removed; otherwise, anyone can have full access to it.

5. Create Pdf in the PdfBox

5.1 insert text in Pdf

In contrast with iText, PdfBox library provides API-based flow operation. No similar Chunk / Paragraph like class. Pdf PDDocument class representation is in memory, the user can write data by manipulating PDPageContentStream class.

Let's look at the code example:

PDDocument document = new PDDocument();
PDPage page = new PDPage();
document.addPage(page);

PDPageContentStream contentStream = new PDPageContentStream(document, page);

contentStream.setFont(PDType1Font.COURIER, 12);
contentStream.beginText();
contentStream.showText("Hello World");
contentStream.endText();
contentStream.close();

document.save("pdfBoxHelloWorld.pdf");
document.close();

5.2 Insert Picture

Insert an image is very simple.

First, we need to load a file and create a PDImageXObject, and then draw on the document (required to provide the exact x, y coordinates).

that's it:

PDDocument document = new PDDocument();
PDPage page = new PDPage();
document.addPage(page);

Path path = Paths.get(ClassLoader.getSystemResource("Java_logo.png").toURI());
PDPageContentStream contentStream = new PDPageContentStream(document, page);
PDImageXObject image
  = PDImageXObject.createFromFile(path.toAbsolutePath().toString(), document);
contentStream.drawImage(image, 0, 0);
contentStream.close();

document.save("pdfBoxImage.pdf");
document.close();

Insert Table 5.3

Unfortunately, PdfBox does not provide any ready-made method allows you to create tables. In this case, we can manually draw - literally, to draw each line, until we are drawing up similar to our dream table.

File Encryption 5.4

PdfBox library provides users with the possibility of adjusting the encryption and file permissions. Compared with iText, it does not require the use of an existing file, because we only use PDDocument. Pdf file permissions handled by AccessPermission class, whether we can modify user settings, extract the contents or print the file.

Then, we create a StandardProtectionPolicy object that will be added to the document based password protection. We can specify two types of passwords. User password, after which users will be able access permissions and owner password has applied to open a file (the file without limitation):

PDDocument document = new PDDocument();
PDPage page = new PDPage();
document.addPage(page);

AccessPermission accessPermission = new AccessPermission();
accessPermission.setCanPrint(false);
accessPermission.setCanModify(false);

StandardProtectionPolicy standardProtectionPolicy
  = new StandardProtectionPolicy("ownerpass", "userpass", accessPermission);
document.protect(standardProtectionPolicy);
document.save("pdfBoxEncryption.pdf");
document.close();

Our example presents a situation, if the user provides user password, you can not modify and print documents.

6 Conclusion

In this tutorial, we discussed ways to create a pdf file in two popular Java library.

Guess you like

Origin www.cnblogs.com/yu-yi/p/11647792.html