Java PDF document copy

This article will introduce to copy the PDF page through a Java program, including:

  • Cross-document copy that copy to the document from the document 1 2
  • Copy within the same document, that is, copied from page A to page B

Use tools: as Free Spire.PDF for the Java (free version)
Jar file access and import methods:
Method 1: through the official website to download jar package. After the download, unzip the file and the lib folder under the Spire.Pdf.jar file into Java programs. Introduced herein below with reference to the effect :( program were introduced into two jar file module)
Java PDF document copy
Method 2: can be installed via maven repository introduced .

Java code examples
[Example 1] Cross-document copying

import com.spire.pdf.*;
import com.spire.pdf.graphics.PdfMargins;
import com.spire.pdf.graphics.PdfTemplate;

import java.awt.*;
import java.awt.geom.Dimension2D;

public class Copy1 {
    public static void main(String[]args){
        //加载两个PDF文档
        PdfDocument pdf1 = new PdfDocument("test1.pdf");
        PdfDocument pdf2 = new PdfDocument("test2.pdf");

        //获取pdf1的第一页,并根据页面创建模板
        PdfPageBase page = pdf1.getPages().get(0);
        Dimension2D size = page.getSize();
        PdfTemplate template = page.createTemplate();

        //在pdf2中第一页插入从复制的pdf1中绘制的模板
        pdf2.getPages().insert(0,size,new PdfMargins(0,0));
        pdf2.getPages().get(0).getCanvas().drawTemplate(template,new Point(0,0));

        //保存pdf2
        pdf2.saveToFile("result.pdf",FileFormat.PDF);
        pdf2.dispose();
    }
}

Cross-document copying effect:
Java PDF document copy
[Example 2] copy in the same document

import com.spire.pdf.*;
import com.spire.pdf.graphics.PdfMargins;
import com.spire.pdf.graphics.PdfTemplate;

import java.awt.*;
import java.awt.geom.Dimension2D;

public class Copy2 {
    public static void main(String[]args){
        //加载测试文档
        PdfDocument pdf = new PdfDocument("test1.pdf");

        //获取第一页,并将于页面创建模板
        PdfPageBase page = pdf.getPages().get(0);
        Dimension2D size = page.getSize();
        PdfTemplate template = page.createTemplate();

        //在文档末循环添加两张绘制好的页面模板
        for(int i=0; i<2; i++){
            page = pdf.getPages().add(size, new PdfMargins(0));
            page.getCanvas().drawTemplate(template, new Point(0, 0));
        }

        //在第一页插入一张绘制好的页面模板
        pdf.getPages().insert(0,size,new PdfMargins(0,0));
        pdf.getPages().get(0).getCanvas().drawTemplate(template,new Point(0,0));

        //保存文档
        pdf.saveToFile("result1.pdf",FileFormat.PDF);
    }
}

Copying effects:
Java PDF document copy

(This article End)

Guess you like

Origin blog.51cto.com/eiceblue/2446805