如果想要实现多个pdf合成,可自己再改改。
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
public class MergePdf {
/** 添加的. */
public static final String COVER = "D:\\gzl\\testPdf/4.pdf";
/** 主pdf. */
public static final String SRC = "D:\\gzl\\testPdf/2.pdf";
/** 存在哪. */
public static final String DEST = "D:\\gzl\\testPdf/7.pdf";
static final String url1="http://gitlab.itextsupport.com/itext/sandbox/raw/master/resources/pdfs/hero.pdf";
static final String url2="http://gitlab.itextsupport.com/itext/sandbox/raw/master/resources/pdfs/hero.pdf";
/**
* 本地合并
* @param src
* @param dest
* @throws IOException
* @throws DocumentException
*/
public static void manipulatePdf(String src, String dest)
throws IOException, DocumentException {
PdfReader cover = new PdfReader(COVER);
PdfReader reader = new PdfReader(src);
Document document = new Document();
PdfCopy copy = new PdfCopy(document, new FileOutputStream(dest));
document.open();
copy.addDocument(cover);
copy.addDocument(reader);
document.close();
cover.close();
reader.close();
}
/**
* Main method.
* @param
* @throws DocumentException
* @throws IOException
*/
public static void main(String[] args)
throws IOException, DocumentException {
File file = new File(DEST);
file.getParentFile().mkdirs();
//manipulatePdf(SRC, DEST);//本地
mergeUrlPdf(url1,url2);//url
}
//url合并,比较适合公司业务
private static void mergeUrlPdf(String url1, String url2) throws IOException, DocumentException{
URL url=new URL(url1);
URLConnection conn = url.openConnection();
InputStream is=conn.getInputStream();
PdfReader cover = new PdfReader(is);
URL u=new URL(url2);
URLConnection con = u.openConnection();
InputStream is2=con.getInputStream();
PdfReader reader = new PdfReader(is2);
Document document = new Document();
PdfCopy copy = new PdfCopy(document, new FileOutputStream(DEST));
document.open();
copy.addDocument(cover);
copy.addDocument(reader);
document.close();
cover.close();
reader.close();
}
}
还可以通过它来convert html格式to pdf
public void createPdf(OutputStream os) throws IOException, DocumentException {
// step 1
Document document = new Document();
// step 2
PdfWriter writer = PdfWriter.getInstance(document, os);
writer.setInitialLeading(12);
// step 3
document.open();
// step 4
XMLWorkerHelper.getInstance().parseXHtml(writer, document,
new FileInputStream(HTML));
// step 5
document.close();
}