itext7 study notes-Chapter 7 Practice &example

    For the examples in this chapter, please refer to the blog post I translated: itext7 study notes-Chapter 7 , which has a detailed explanation. If you don't understand, you can comment or send a private message to me!

Example 1: Create PDF/UA document

    On the basis of the fox and dog race in the first chapter, we create a PDF/UA standard document, the code is as follows:

import com.itextpdf.kernel.pdf.*;
import com.itextpdf.kernel.utils.PdfMerger;
import com.itextpdf.pdfa.PdfADocument;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;


public class C07E04_MergePDFADocuments {
    
    
    public static final String INTENT = "src/main/resources/color/sRGB_CS_profile.icm";

    public static final String SRC1 = "src/main/resources/pdf/quick_brown_fox_PDFA-1a.pdf";
    public static final String SRC2 = "src/main/resources/pdf/united_states_PDFA-1a.pdf";
    public static final String DEST = "results/chapter07/merged_PDFA-1a_documents.pdf";

    public static void main(String args[]) throws IOException {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new C07E04_MergePDFADocuments().createPdf(DEST);
    }

    public void createPdf(String dest) throws IOException {
        //Initialize PDFA document with output intent
        PdfADocument pdf = new PdfADocument(new PdfWriter(dest),
                PdfAConformanceLevel.PDF_A_1A,
                new PdfOutputIntent("Custom", "", "http://www.color.org",
                        "sRGB IEC61966-2.1", new FileInputStream(INTENT)));

        //Setting some required parameters
        pdf.setTagged();
        pdf.getCatalog().setLang(new PdfString("en-US"));
        pdf.getCatalog().setViewerPreferences(
                new PdfViewerPreferences().setDisplayDocTitle(true));
        PdfDocumentInfo info = pdf.getDocumentInfo();
        info.setTitle("iText7 PDF/A-1a example");

        //Create PdfMerger instance
        PdfMerger merger = new PdfMerger(pdf);
        //Add pages from the first document
        PdfDocument firstSourcePdf = new PdfDocument(new PdfReader(SRC1));
        merger.merge(firstSourcePdf, 1, firstSourcePdf.getNumberOfPages());
        //Add pages from the second pdf document
        PdfDocument secondSourcePdf = new PdfDocument(new PdfReader(SRC2));
        merger.merge(secondSourcePdf, 1, secondSourcePdf.getNumberOfPages());

        //Close the documents
        firstSourcePdf.close();
        secondSourcePdf.close();
        pdf.close();
    }
}

## Example 2: Create PDF/A-1b document

    PDF/A-1 is a part of ISO 19005, and there are also a and b points. We create PDF/A-1b standard documents with the following code:

import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfAConformanceLevel;
import com.itextpdf.kernel.pdf.PdfOutputIntent;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Text;
import com.itextpdf.pdfa.PdfADocument;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;


public class C07E02_QuickBrownFox_PDFA_1b {
    public static final String DOG = "src/main/resources/img/dog.bmp";
    public static final String FOX = "src/main/resources/img/fox.bmp";
    public static final String FONT = "src/main/resources/font/FreeSans.ttf";
    public static final String INTENT = "src/main/resources/color/sRGB_CS_profile.icm";

    public static final String DEST = "results/chapter07/quick_brown_fox_PDFA-1b.pdf";

    public static void main(String args[]) throws IOException {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new C07E02_QuickBrownFox_PDFA_1b().createPdf(DEST);
    }

    public void createPdf(String dest) throws IOException {
        //Initialize PDFA document with output intent
        PdfADocument pdf = new PdfADocument(new PdfWriter(dest),
                PdfAConformanceLevel.PDF_A_1B,
                new PdfOutputIntent("Custom", "", "http://www.color.org",
                        "sRGB IEC61966-2.1", new FileInputStream(INTENT)));
        Document document = new Document(pdf);

        //Fonts need to be embedded
        PdfFont font = PdfFontFactory.createFont(FONT, PdfEncodings.WINANSI, true);
        Paragraph p = new Paragraph();
        p.setFont(font);
        p.add(new Text("The quick brown "));
        Image foxImage = new Image(ImageDataFactory.create(FOX));
        p.add(foxImage);
        p.add(" jumps over the lazy ");
        Image dogImage = new Image(ImageDataFactory.create(DOG));
        p.add(dogImage);

        document.add(p);
        document.close();
    }
}

Example 3: Create PDF/A-1a document

    PDF/A-1 is a part of ISO 19005, and there are also a and b points. We create PDF/A-1a standard documents, the code is as follows:

import  com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfAConformanceLevel;
import com.itextpdf.kernel.pdf.PdfOutputIntent;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Text;
import com.itextpdf.pdfa.PdfADocument;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;


public class C07E02_QuickBrownFox_PDFA_1a {
    public static final String DOG = "src/main/resources/img/dog.bmp";
    public static final String FOX = "src/main/resources/img/fox.bmp";
    public static final String FONT = "src/main/resources/font/FreeSans.ttf";
    public static final String INTENT = "src/main/resources/color/sRGB_CS_profile.icm";

    public static final String DEST = "results/chapter07/quick_brown_fox_PDFA-1a.pdf";

    public static void main(String args[]) throws IOException {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new C07E02_QuickBrownFox_PDFA_1a().createPdf(DEST);
    }

    public void createPdf(String dest) throws IOException {
        //Initialize PDFA document with output intent
        PdfADocument pdf = new PdfADocument(new PdfWriter(dest),
                PdfAConformanceLevel.PDF_A_1A,
                new PdfOutputIntent("Custom", "", "http://www.color.org",
                        "sRGB IEC61966-2.1", new FileInputStream(INTENT)));
        Document document = new Document(pdf);

        //Setting some required parameters
        pdf.setTagged();

        //Fonts need to be embedded
        PdfFont font = PdfFontFactory.createFont(FONT, PdfEncodings.WINANSI, true);
        Paragraph p = new Paragraph();
        p.setFont(font);
        p.add(new Text("The quick brown "));
        Image foxImage = new Image(ImageDataFactory.create(FOX));
        //Set alt text
        foxImage.getAccessibilityProperties().setAlternateDescription("Fox");
        p.add(foxImage);
        p.add(" jumps over the lazy ");
        Image dogImage = new Image(ImageDataFactory.create(DOG));
        //Set alt text
        dogImage.getAccessibilityProperties().setAlternateDescription("Dog");
        p.add(dogImage);

        document.add(p);
        document.close();
    }
}

Example 4: Create PDF/A-1a document

    PDF/A-2 and PDF/A-3 are enhanced parts of ISO 19005. 3 to 2 has no format restrictions on attachments. We create PDF/A-3a standard documents with the following code:

import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.*;
import com.itextpdf.kernel.pdf.filespec.PdfFileSpec;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.property.HorizontalAlignment;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.pdfa.PdfADocument;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.StringTokenizer;

public class C07E03_UnitedStates_PDFA_3a {
    public static final String DATA = "src/main/resources/data/united_states.csv";
    public static final String FONT = "src/main/resources/font/FreeSans.ttf";
    public static final String BOLD_FONT = "src/main/resources/font/FreeSansBold.ttf";
    public static final String INTENT = "src/main/resources/color/sRGB_CS_profile.icm";


    public static final String DEST = "results/chapter07/united_states_PDFA-3a.pdf";

    public static void main(String args[]) throws IOException {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new C07E03_UnitedStates_PDFA_3a().createPdf(DEST);
    }

    public void createPdf(String dest) throws IOException {
        PdfADocument pdf = new PdfADocument(new PdfWriter(dest),
                PdfAConformanceLevel.PDF_A_3A,
                new PdfOutputIntent("Custom", "", "http://www.color.org",
                        "sRGB IEC61966-2.1", new FileInputStream(INTENT)));
        Document document = new Document(pdf, PageSize.A4.rotate());
        document.setMargins(20, 20, 20, 20);

        //Setting some required parameters
        pdf.setTagged();
        pdf.getCatalog().setLang(new PdfString("en-US"));
        pdf.getCatalog().setViewerPreferences(
                new PdfViewerPreferences().setDisplayDocTitle(true));
        PdfDocumentInfo info = pdf.getDocumentInfo();
        info.setTitle("iText7 PDF/A-3 example");

        //Add attachment
        PdfDictionary parameters = new PdfDictionary();
        parameters.put(PdfName.ModDate, new PdfDate().getPdfObject());
        PdfFileSpec fileSpec = PdfFileSpec.createEmbeddedFileSpec(
                pdf, Files.readAllBytes(Paths.get(DATA)), "united_states.csv",
                "united_states.csv", new PdfName("text/csv"), parameters,
                PdfName.Data, false);
        fileSpec.put(new PdfName("AFRelationship"), new PdfName("Data"));
        pdf.addFileAttachment("united_states.csv", fileSpec);
        PdfArray array = new PdfArray();
        array.add(fileSpec.getPdfObject().getIndirectReference());
        pdf.getCatalog().put(new PdfName("AF"), array);

        //Embed fonts
        PdfFont font = PdfFontFactory.createFont(FONT, true);
        PdfFont bold = PdfFontFactory.createFont(BOLD_FONT, true);

        // Create content
        Table table = new Table(new float[]{
   
   4, 1, 3, 4, 3, 3, 3, 3, 1});
        table.setWidthPercent(100);
        BufferedReader br = new BufferedReader(new FileReader(DATA));
        String line = br.readLine();
        process(table, line, bold, true);
        while ((line = br.readLine()) != null) {
            process(table, line, font, false);
        }
        br.close();
        document.add(table);

        //Close document
        document.close();
    }

    public void process(Table table, String line, PdfFont font, boolean isHeader) {
        StringTokenizer tokenizer = new StringTokenizer(line, ";");
        while (tokenizer.hasMoreTokens()) {
            if (isHeader) {
                table.addHeaderCell(new Cell().setHorizontalAlignment(HorizontalAlignment.CENTER).add(new Paragraph(tokenizer.nextToken()).setHorizontalAlignment(HorizontalAlignment.CENTER).setFont(font)));
            } else {
                table.addCell(new Cell().setHorizontalAlignment(HorizontalAlignment.CENTER).add(new Paragraph(tokenizer.nextToken()).setHorizontalAlignment(HorizontalAlignment.CENTER).setFont(font)));
            }
        }
    }
}

Example 5: Stitching PDF/A documents

    When stitching PDF/A files, the most worthy of our attention is that each document we stitched must be a PDF/A file. Here, we stitch together two PDF/A-1A documents, the code is as follows:

import com.itextpdf.kernel.pdf.*;
import com.itextpdf.kernel.utils.PdfMerger;
import com.itextpdf.pdfa.PdfADocument;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;


public class C07E04_MergePDFADocuments {
    
    
    public static final String INTENT = "src/main/resources/color/sRGB_CS_profile.icm";

    public static final String SRC1 = "src/main/resources/pdf/quick_brown_fox_PDFA-1a.pdf";
    public static final String SRC2 = "src/main/resources/pdf/united_states_PDFA-1a.pdf";
    public static final String DEST = "results/chapter07/merged_PDFA-1a_documents.pdf";

    public static void main(String args[]) throws IOException {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new C07E04_MergePDFADocuments().createPdf(DEST);
    }

    public void createPdf(String dest) throws IOException {
        //Initialize PDFA document with output intent
        PdfADocument pdf = new PdfADocument(new PdfWriter(dest),
                PdfAConformanceLevel.PDF_A_1A,
                new PdfOutputIntent("Custom", "", "http://www.color.org",
                        "sRGB IEC61966-2.1", new FileInputStream(INTENT)));

        //Setting some required parameters
        pdf.setTagged();
        pdf.getCatalog().setLang(new PdfString("en-US"));
        pdf.getCatalog().setViewerPreferences(
                new PdfViewerPreferences().setDisplayDocTitle(true));
        PdfDocumentInfo info = pdf.getDocumentInfo();
        info.setTitle("iText7 PDF/A-1a example");

        //Create PdfMerger instance
        PdfMerger merger = new PdfMerger(pdf);
        //Add pages from the first document
        PdfDocument firstSourcePdf = new PdfDocument(new PdfReader(SRC1));
        merger.merge(firstSourcePdf, 1, firstSourcePdf.getNumberOfPages());
        //Add pages from the second pdf document
        PdfDocument secondSourcePdf = new PdfDocument(new PdfReader(SRC2));
        merger.merge(secondSourcePdf, 1, secondSourcePdf.getNumberOfPages());

        //Close the documents
        firstSourcePdf.close();
        secondSourcePdf.close();
        pdf.close();
    }
}

Example code download

    The code for this chapter can be downloaded at the following address (IDEA project): iText7——Chapter 7 Source Code Project

Guess you like

Origin blog.csdn.net/u012397189/article/details/78885790