使用itextpdf操作pdf

2021-02-12 10:03:35 浏览数 (1)

使用maven引入jar

代码语言:javascript复制
<dependency>
    <groupId>com.itextpdfgroupId>
    <artifactId>itextpdfartifactId>
    <version>5.2.0version>
dependency>
<dependency>
    <groupId>com.itextpdfgroupId>
    <artifactId>itext-asianartifactId>
    <version>5.2.0version>
dependency>

创建exportToPDF工具类

代码语言:javascript复制
package com.os.core.util.file.exportPdf;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.FontSelector;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

/**
 * Created by PengSongHe on 2016/10/20 0020.
 */
public class exportToPDF {
    public static void main(String[] args) {
        try {

            Document document = new Document();//默认A4
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("d:/HelloWorld.pdf"));
            writer.setPdfVersion(PdfWriter.PDF_VERSION_1_7);
            document.addCreationDate();
            document.addCreator("飞翔家族");
            document.addTitle("export pdf");
            document.addKeywords("export");
            document.addSubject("飞翔家族 export pdf");
            document.open();

//处理中文,需要itextasian.jar支持

            FontSelector selector = new FontSelector();
            selector.addFont(FontFactory.getFont(FontFactory.TIMES_ROMAN, 12));
            selector.addFont(FontFactory.getFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED));
            Phrase phrase = selector.process("HelloWord!你好。u4fddu5b58");
            document.add(new Paragraph(phrase));
            //添加新页
            //document.newPage();
            //writer.setPageEmpty(false);
            //document.add(new Paragraph("New page"));
            document.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

}

0 人点赞