java 通过 itext生成pdf添加,插入文字,图片

准备工作
引用pom

        
        
            com.itextpdf
            itextpdf
            5.5.11
        
        
        
            com.itextpdf
            itext-asian
            5.2.0
        
        
        
            com.itextpdf.tool
            xmlworker
            5.5.11
        

1. 生成导出
写入到本地的文件中,不存在会自动创建,存在则覆盖,注意双斜杠的写法
两种输入方式:
//直接输出到本地文件
PdfWriter.getInstance(document, new FileOutputStream("F:\\Hello simplePDF.pdf"));
//byte[]格式文件流输出
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
byte[] buffer = byteStream.toByteArray();
public void createInstructionPDF() {
    try {
        Document document = new Document(PageSize.A4, 60, 60, 60, 60);
        //PdfWriter.getInstance(document, new FileOutputStream("F:\\Hello simplePDF.pdf"));
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        PdfWriter.getInstance(document, byteStream);
        document.addAuthor("XXX");
        document.addCreationDate();
        document.addCreator("XXX");
        document.addSubject("XXXXXX");
        document.addTitle("XXXXXX");
        document.addHeader("Expires", "0");
        document.open();
        //createPdfContent(document);
        document.close();
        byte[] buffer = byteStream.toByteArray();
        FileOutputStream fos = new FileOutputStream("F:\\Instruction.pdf");
        fos.write(buffer);
        fos.close();
    } catch (Exception ex) {
    }
    return result;
}

2. 设置字体

BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);//中文字体
Font fontTitle = new Font(bfChinese, 24, Font.BOLD);
Font fontBig = new Font(bfChinese, 18, Font.NORMAL);

3. 添加文本和段落

 private void createPdfContent(Document document, Font fontTitle,Font fontNormal) {
        try {
            Chunk glue = new Chunk(new VerticalPositionMark());//用来隔断到一行的两边
            int timeOffSet = 3600;
            Paragraph paragraph1 = new Paragraph("上海旅行攻略", fontTitle);
            String strTimeOff = "中国比" + cityName + (timeOffSet < 0 ? "快" + Math.abs(timeOffSet) + "小时" : "慢" + Math.abs(timeOffSet) + "小时");
            Chunk timeChunk = new Chunk(strTimeOff, fontNormal);
            paragraph1.add(glue);
            paragraph1.add(timeChunk);
            paragraph1.setSpacingAfter(10);//距离后面行距
            document.add(paragraph1);
        } catch (Exception ex) {
        }
    }

4. 添加图片

    private void createPic(Document document) {
        String headPicture = "图片地址链接";
        try {
            Image image = Image.getInstance(headPicture);
            float documentWidth = document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin();
            float documentHeight = documentWidth / 580 * 320;//重新设置宽高
            image.scaleAbsolute(documentWidth, documentHeight);//重新设置宽高
            document.add(image);
        } catch (Exception ex) {

        }
    }



你可能感兴趣的:(JAVA)