itext5和itext7操作pdf平铺和图层叠加(tiling, and N-upping)

区别

itext5 生成pdf版本:1.4(Acrobat5.x)
itext7 生成pdf版本:1.7(Acrobat8.x)

iText7生成的pdf文件大, itext7 Java库更加系统和完善

iText测试版本和功能描述

itext5

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.13</version>
</dependency>

itext7

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itext7-core</artifactId>
    <version>7.1.8</version>
    <type>pom</type>
</dependency>

描述: pdf稿件平铺和生成条形码

示例代码

itext5

package com.demo.controller;

import com.itextpdf.text.*;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;

import java.io.FileOutputStream;
import java.io.IOException;

import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.File;
import java.util.ArrayList;
import java.util.List;



public class HelloController {

    public static final String OUTDIR = "results/big/";

    private float _PT_CM_RATE = 0.352736F;

    private static float _PILLOW_HEIGHT = 70F / 0.352736F;
    private static float _PILLOW_WIDTH = 47F / 0.352736F;


    public static void main(String args[]) throws IOException {
        File file = new File(OUTDIR);
        file.getParentFile().mkdirs();
        try {
            double random = Math.random();
            new HelloController().createCodePdf(OUTDIR+"all"+random+".pdf");
            new HelloController().createRowPdf(OUTDIR+"row"+random+".pdf");
        }catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
    }

    public void createCodePdf(String dest) throws IOException, DocumentException {

        List<String> arrayList = new ArrayList<String>();
        arrayList.add("results/test_three_01.pdf");
        arrayList.add("results/test_three_02.pdf");
        arrayList.add("results/test_three_03.pdf");
        arrayList.add("results/test_three_04.pdf");
        arrayList.add("results/test_three_05.pdf");
        arrayList.add("results/test_three_06.pdf");
        arrayList.add("results/test_three_07.pdf");
        arrayList.add("results/test_three_08.pdf");
        arrayList.add("results/test_three_09.pdf");
        arrayList.add("results/test_three_10.pdf");

        //生成文件的pdfDoc对象
        Document document = new Document(new Rectangle(707 / _PT_CM_RATE, 1081 / _PT_CM_RATE));
        PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(dest));
        document.open();
        PdfContentByte canvas = pdfWriter.getDirectContent();

        //1.添加两边黑光标
        PdfReader pdfBlack = new PdfReader("results/black_47.pdf");
        Rectangle pageSize = pdfBlack.getPageSize(1);
        final float pdfBlackWidth = pageSize.getWidth();

        PdfImportedPage pageBlackCopy = pdfWriter.getImportedPage(pdfBlack, 1);


        int rowWorkNum = 18;
        int rowCodeNum = 5;
        //2.遍历稿件list
        for (int i = 1; i <= rowWorkNum+rowCodeNum; i++)
        {
            canvas.addTemplate(pageBlackCopy, 0, _PILLOW_WIDTH*(i-1) );
            canvas.addTemplate(pageBlackCopy,_PILLOW_HEIGHT*10+pdfBlackWidth,_PILLOW_WIDTH*(i-1));
        }
        int j = 0;
        PdfImportedPage workPdfPage;
        for (String work : arrayList) {
            //读取稿件内容
            PdfReader workPdf = new PdfReader(work);
            workPdfPage = pdfWriter.getImportedPage(workPdf, 1);
            for (int i = 1; i <= rowWorkNum; i++) {
                canvas.addTemplate(workPdfPage, 0, -1, 1, 0, _PILLOW_HEIGHT * j + pdfBlackWidth, _PILLOW_WIDTH * (i + 5));
            }
            j++;
        }

        //3.遍历条形码
        //遍历条形码底图
        PdfReader pdfBlackCode = new PdfReader("results/black_100.pdf");
        PdfImportedPage pageBlackCodeCopy = pdfWriter.getImportedPage(pdfBlackCode, 1);
        for(int jj=1; jj<=10; jj++){

            Barcode128 barcode = new Barcode128();
            barcode.setCodeType(Barcode.CODE128);
            barcode.setBarHeight(14);
            barcode.setX(0.4F);
            barcode.setBaseline(23f);
            barcode.setCode("1954745454544_3-"+jj);
            barcode.setTextAlignment(0);
            PdfTemplate templateWithBarcode = barcode.createTemplateWithBarcode(canvas, BaseColor.BLACK, BaseColor.BLACK);
            barcode.setFont(BaseFont.createFont("c:/windows/fonts/simkai.ttf", BaseFont.IDENTITY_H,false));
            barcode.setAltText("进口量煎熬副科级第三方");
            PdfTemplate templateWithBarcodeText = barcode.createTemplateWithBarcode(canvas, BaseColor.BLACK, BaseColor.BLACK);
            barcode.setAltText("");
            PdfTemplate templateWithBarcodeNone = barcode.createTemplateWithBarcode(canvas, BaseColor.BLACK, BaseColor.BLACK);
            for(int i=1; i<=rowCodeNum; i++){
                canvas.addTemplate(pageBlackCodeCopy,0,-1,1,0,(jj-1)*_PILLOW_HEIGHT+pdfBlackWidth,(i)*_PILLOW_WIDTH);
                canvas.addTemplate(templateWithBarcodeText, 0, -1, 1, 0, 52 + (jj - 1) * _PILLOW_HEIGHT + pdfBlackWidth, (i) * _PILLOW_WIDTH - 25);
                canvas.addTemplate(templateWithBarcode, 0, -1, 1, 0, 67 + (jj - 1) * _PILLOW_HEIGHT + pdfBlackWidth, (i) * _PILLOW_WIDTH - 25);
                canvas.addTemplate(templateWithBarcodeNone, 0, -1, 1, 0, 82 + (jj - 1) * _PILLOW_HEIGHT + pdfBlackWidth, (i) * _PILLOW_WIDTH - 25);
                canvas.addTemplate(templateWithBarcodeNone, 0, -1, 1, 0, 97 + (jj - 1) * _PILLOW_HEIGHT + pdfBlackWidth, (i) * _PILLOW_WIDTH - 25);
            }
        }

        //4.关闭资源
        document.close();
        pdfBlack.close();
        pdfBlackCode.close();

    }

    public void createRowPdf(String dest) throws IOException , DocumentException{

        List<String> arrayList = new ArrayList<String>();
        arrayList.add("results/test_three_01.pdf");
        arrayList.add("results/test_three_02.pdf");
        arrayList.add("results/test_three_03.pdf");
        arrayList.add("results/test_three_04.pdf");
        arrayList.add("results/test_three_05.pdf");
        arrayList.add("results/test_three_06.pdf");
        arrayList.add("results/test_three_07.pdf");
        arrayList.add("results/test_three_08.pdf");
        arrayList.add("results/test_three_09.pdf");
        arrayList.add("results/test_three_10.pdf");

        //生成文件的pdfDoc对象
        Document document = new Document(new Rectangle(707 / _PT_CM_RATE, 47/ _PT_CM_RATE));
        PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(dest));
        document.open();
        PdfContentByte canvas = pdfWriter.getDirectContent();

        //1.添加两边黑光标
        PdfReader pdfBlack = new PdfReader("results/black_47.pdf");
        Rectangle pageSize = pdfBlack.getPageSize(1);
        final float pdfBlackWidth = pageSize.getWidth();

        PdfImportedPage pageBlackCopy = pdfWriter.getImportedPage(pdfBlack, 1);


        int rowWorkNum = 1;
        int rowCodeNum = 0;
        //2.遍历稿件list
        for (int i = 1; i <= rowWorkNum+rowCodeNum; i++)
        {
            canvas.addTemplate(pageBlackCopy, 0, _PILLOW_WIDTH*(i-1) );
            canvas.addTemplate(pageBlackCopy,_PILLOW_HEIGHT*10+pdfBlackWidth,_PILLOW_WIDTH*(i-1));
        }
        int j = 0;
        PdfImportedPage workPdfPage;
        for (String work : arrayList) {
            //读取稿件内容
            PdfReader workPdf = new PdfReader(work);
            workPdfPage = pdfWriter.getImportedPage(workPdf, 1);
            for (int i = 1; i <= rowWorkNum; i++) {
                canvas.addTemplate(workPdfPage, 0, -1, 1, 0, _PILLOW_HEIGHT * j + pdfBlackWidth, _PILLOW_WIDTH * (i));
            }
            j++;
        }
        //关闭资源
        document.close();
        pdfBlack.close();

    }

}

itext7

package com.demo.controller;
import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.io.font.constants.StandardFonts;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.barcodes.Barcode128;
import com.itextpdf.barcodes.Barcode1D;
import com.itextpdf.io.font.FontConstants;
import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageType;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.kernel.pdf.xobject.PdfFormXObject;
import com.itextpdf.kernel.geom.AffineTransform;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.kernel.PdfException;
import com.itextpdf.kernel.colors.Color;
import com.itextpdf.kernel.colors.ColorConstants;
import com.itextpdf.kernel.colors.DeviceRgb;

import org.apache.pdfbox.cos.COSBase;
import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.itextpdf.layout.element.Text;

import static com.itextpdf.svg.SvgConstants.Tags.IMAGE;


public class HelloController {

    public static final String DEST = "results/big/wwww"+Math.random()+".pdf";

    private float _PT_CM_RATE = 0.352736F;

    private static float _PILLOW_HEIGHT = 70F / 0.352736F;
    private static float _PILLOW_WIDTH = 47F / 0.352736F;


    public static void main(String args[]) throws IOException {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
//        new HelloController().createCodePdf(DEST);
        new HelloController().createRowPdf(DEST);
    }

    public void createCodePdf(String dest) throws IOException {

        List<String> arrayList = new ArrayList<String>();
        arrayList.add("results/test_three_01.pdf");
        arrayList.add("results/test_three_02.pdf");
        arrayList.add("results/test_three_03.pdf");
        arrayList.add("results/test_three_04.pdf");
        arrayList.add("results/test_three_05.pdf");
        arrayList.add("results/test_three_06.pdf");
        arrayList.add("results/test_three_07.pdf");
        arrayList.add("results/test_three_08.pdf");
        arrayList.add("results/test_three_09.pdf");
        arrayList.add("results/test_three_10.pdf");

        //生成文件的pdfDoc对象
        PdfWriter dfWriter = new PdfWriter(dest);
        dfWriter.setSmartMode(true);
        PdfDocument pdf = new PdfDocument(dfWriter);

        PageSize nUpPageSize = new PageSize(707 / _PT_CM_RATE, 1081 / _PT_CM_RATE);
//        PageSize nUpPageSize = new PageSize(707 / _PT_CM_RATE, 510 / _PT_CM_RATE);
        PdfPage page = pdf.addNewPage(nUpPageSize);

        //画布的生成
        PdfCanvas canvas = new PdfCanvas(page);

        //Scale page
        AffineTransform transformationMatrix = AffineTransform.getScaleInstance(1, 1);
        canvas.concatMatrix(transformationMatrix);//不旋转

        //添加右侧黑光标
        PdfDocument pdfBlack = new PdfDocument(new PdfReader("results/black_47.pdf"));
        PdfPage blackPage = pdfBlack.getPage(1);
        Rectangle origBlack = blackPage.getPageSize();
        PdfFormXObject pageBlackCopy = blackPage.copyAsFormXObject(pdf);


        int rowWorkNum = 18;
        int rowCodeNum = 5;
        //遍历稿件list
        for (int i = 1; i <= rowWorkNum; i++)
            canvas.addXObject(pageBlackCopy, 0, _PILLOW_WIDTH*(i+4) );
        int j = 0;
        for (String work : arrayList) {
            //System.out.println(work);
            //读取稿件内容
            PdfDocument workPdf = new PdfDocument(new PdfReader(work));
            PdfPage workPdfPage = workPdf.getPage(1);
            PdfFormXObject workPdfPageForm = workPdfPage.copyAsFormXObject(pdf);
            for (int i = 1; i <= rowWorkNum; i++) {

                canvas.addXObject(workPdfPageForm, 0, -1, 1, 0, _PILLOW_HEIGHT * j + origBlack.getWidth(), _PILLOW_WIDTH * (i + 5));
            }
            workPdf.close();
            j++;
        }
        for (int i = 1; i <= rowWorkNum; i++)
            canvas.addXObject(pageBlackCopy,_PILLOW_HEIGHT*10+origBlack.getWidth(),_PILLOW_WIDTH*(i+4));

        //遍历条形码
        //遍历条形码底图
        PdfDocument codeBackPdf = new PdfDocument(new PdfReader("results/black_100.pdf"));
        PdfPage codeBackPage = codeBackPdf.getPage(1);
        Rectangle codeBackPageRectangle = codeBackPage.getPageSize();
        PdfFormXObject codeBackPageForm = codeBackPage.copyAsFormXObject(pdf);

        for(int i=1; i<=rowCodeNum; i++){

            canvas.addXObject(pageBlackCopy, 0, _PILLOW_WIDTH*(i-1) );
            for(int jj=1; jj<=10; jj++){
                canvas.addXObject(codeBackPageForm,0,-1,1,0,(jj-1)*_PILLOW_HEIGHT+origBlack.getWidth(),(i)*_PILLOW_WIDTH);

                String myString = "1954745454544_3-1";
                Barcode128 barcode = new Barcode128(pdf);
                barcode.setCode(myString);
                barcode.setCodeType(Barcode128.CODE128);
                barcode.setBaseline(23f);
                barcode.setAltText("进口量煎熬副科级第三方");
                barcode.setFont(PdfFontFactory.createFont("c:/windows/fonts/simkai.ttf", PdfEncodings.IDENTITY_H,false));
                barcode.setTextAlignment(Barcode1D.ALIGN_LEFT);
                barcode.setBarHeight(14);
                barcode.setX(0.45F);

                PdfFormXObject pdfImg = barcode.createFormXObject(pdf);
                barcode.setAltText("1954745454544_3-1");

                PdfFormXObject pdfImgCode = barcode.createFormXObject(pdf);
                barcode.setAltText("");
                PdfFormXObject pdfImgOnly = barcode.createFormXObject(pdf);
                //canvas.add(p);
                canvas.addXObject(pdfImg,0,-1,1,0,52+(jj-1)*_PILLOW_HEIGHT+origBlack.getWidth(),(i)*_PILLOW_WIDTH-25);
                canvas.addXObject(pdfImgCode,0,-1,1,0,67+(jj-1)*_PILLOW_HEIGHT+origBlack.getWidth(),(i)*_PILLOW_WIDTH-25);
                canvas.addXObject(pdfImgOnly,0,-1,1,0,82+(jj-1)*_PILLOW_HEIGHT+origBlack.getWidth(),(i)*_PILLOW_WIDTH-25);
                canvas.addXObject(pdfImgOnly,0,-1,1,0,97+(jj-1)*_PILLOW_HEIGHT+origBlack.getWidth(),(i)*_PILLOW_WIDTH-25);

            }
            canvas.addXObject(pageBlackCopy,_PILLOW_HEIGHT*10+origBlack.getWidth(),_PILLOW_WIDTH*(i-1));

        }
        pdfBlack.close();
        pdf.close();

    }
    public void createRowPdf(String dest) throws IOException {

        List<String> arrayList = new ArrayList<String>();
        arrayList.add("results/test_three_01.pdf");
        arrayList.add("results/test_three_02.pdf");
        arrayList.add("results/test_three_03.pdf");
        arrayList.add("results/test_three_04.pdf");
        arrayList.add("results/test_three_05.pdf");
        arrayList.add("results/test_three_06.pdf");
        arrayList.add("results/test_three_07.pdf");
        arrayList.add("results/test_three_08.pdf");
        arrayList.add("results/test_three_09.pdf");
        arrayList.add("results/test_three_10.pdf");

        //生成文件的pdfDoc对象
        PdfDocument pdf = new PdfDocument(new PdfWriter(dest));

        System.out.println(pdf.getPdfVersion());


        PageSize nUpPageSize = new PageSize(707 / _PT_CM_RATE, 47 / _PT_CM_RATE);
        PdfPage page = pdf.addNewPage(nUpPageSize);

        //画布的生成
        PdfCanvas canvas = new PdfCanvas(page);

        //Scale page
        AffineTransform transformationMatrix = AffineTransform.getScaleInstance(1, 1);
        canvas.concatMatrix(transformationMatrix);//不旋转

        //添加右侧黑光标
        PdfDocument pdfBlack = new PdfDocument(new PdfReader("results/black_47.pdf"));
        PdfPage blackPage = pdfBlack.getPage(1);
        Rectangle origBlack = blackPage.getPageSize();
        PdfFormXObject pageBlackCopy = blackPage.copyAsFormXObject(pdf);

        canvas.addXObject(pageBlackCopy, 0, 0);

        //遍历稿件list
        int j = 0;
        for (String work : arrayList) {
            //读取稿件内容
            PdfDocument workPdf = new PdfDocument(new PdfReader(work));
            PdfPage workPdfPage = workPdf.getPage(1);
            //pdf转化为图片资源
//            byte[] contentBytes = workPdfPage.getContentBytes();
//            ImageData image = ImageDataFactory.create(contentBytes);
//            canvas.addImage(image, 0,-1,1,0,_PILLOW_HEIGHT*j+origBlack.getWidth(),_PILLOW_WIDTH);

            //pdf转化为formX
            PdfFormXObject workPdfPageForm = workPdfPage.copyAsFormXObject(pdf);
            canvas.addXObject(workPdfPageForm, 0,-1,1,0,_PILLOW_HEIGHT*j+origBlack.getWidth(),_PILLOW_WIDTH);
            workPdf.close();
            j++;
        }
        canvas.addXObject(pageBlackCopy,_PILLOW_HEIGHT*10+origBlack.getWidth(),0);

        pdfBlack.close();
        pdf.close();
    }
}

参考文章

https://itextpdf.com/en/resources/books/itext-7-jump-start-tutorial-java/chapter-6-reusing-existing-pdf-documents

https://itextpdf.com/en/resources/examples/itext-5-legacy/chapter-6-working-existing-pdfs

posted @ 2019-12-24 17:12  sentangle  阅读(2947)  评论(0编辑  收藏  举报