java使用itext生成pdf

效果:

java使用itext生成pdf_第1张图片

maven依赖

      
        
        
			com.itextpdf
			itextpdf
			5.5.13.3
		

 代码:

import cn.hutool.core.date.DateUtil;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import lombok.SneakyThrows;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @projectName: util-cloud
 * @package: com.zxw.controller
 * @className: PDFController
 * @author: zhangxuewei
 * @description: TODO
 * @date: 2023/9/8 9:52
 * @version: 1.0
 */
@RestController
@RequestMapping("/pdf")
public class PDFController {



@GetMapping("/generate-pdf3")
    public void generatePdf3(HttpServletResponse response) throws IOException, DocumentException {
        // 设置响应内容类型为PDF
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "attachment; filename=sample.pdf");

        // 设置中文字体,这里使用了 楷体常规
        BaseFont bf = BaseFont.createFont("c://windows//fonts//simkai.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        Font font = new Font(bf, 12);

        // 创建PDF文档
        Document document = new Document();
        PdfWriter pdfWriter = PdfWriter.getInstance(document, response.getOutputStream());

        // 添加水印
        pdfWriter.setPageEvent(new WatermarkPageEvent());

        // 打开文档
        document.open();
        // 添加中文内容
        Paragraph paragraph = new Paragraph("你好,iText 5!", font);
        document.add(paragraph);

        font.setColor(BaseColor.GREEN);
        Paragraph paragraphc = new Paragraph("这是一个字体颜色为绿色的段落", font);
        document.add(paragraphc);

        Font font2 = new Font(bf, 18, Font.BOLD);
        Paragraph paragraph2 = new Paragraph("这是一个字体大小为18的粗体段落", font2);
        document.add(paragraph2);

        Font fontb = new Font(bf, 12);
        Chunk yellowChunk = new Chunk(" 这是一个背景颜色为黄色的段落 ", fontb);
        yellowChunk.setBackground(BaseColor.YELLOW);
        Paragraph paragraphcb = new Paragraph();
        paragraphcb.add(yellowChunk);
        document.add(paragraphcb);


        // 创建表格
        PdfPTable table = new PdfPTable(3); // 3列的表格
        table.setWidthPercentage(100);
        table.setSpacingBefore(10f);
        table.setSpacingAfter(10f);

        // 第一行数据
        PdfPCell cell1 = new PdfPCell(new Paragraph("列1"));
        cell1.setBorderColor(BaseColor.BLUE);
        cell1.setPadding(5);

        PdfPCell cell2 = new PdfPCell(new Paragraph("列2"));
        cell2.setBorderColor(BaseColor.RED);
        cell2.setPadding(5);

        PdfPCell cell3 = new PdfPCell(new Paragraph("列3"));
        cell3.setBorderColor(BaseColor.GREEN);
        cell3.setPadding(5);

        table.addCell(cell1);
        table.addCell(cell2);
        table.addCell(cell3);
        document.add(table);

        // 关闭文档
        document.close();
    }


    // 自定义页面事件类来添加水印
    static class WatermarkPageEvent extends PdfPageEventHelper {
        @SneakyThrows
        @Override
        public void onEndPage(PdfWriter writer, Document document) {
            BaseFont bf = BaseFont.createFont("c://windows//fonts//simkai.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            Font font = new Font(bf, 24, Font.NORMAL, new BaseColor(128, 128, 128));
            // 获取页面大小
            Rectangle pageSize = document.getPageSize();
            String now = DateUtil.now();
            String info = "        张学伟 " + now;
            for (int i = 0; i < 5; i++) {
                info += info;
            }

            // 创建水印文本
            PdfContentByte content = writer.getDirectContentUnder();
            PdfGState gs = new PdfGState();
            gs.setFillOpacity(0.4f); // 设置透明度
            content.setGState(gs);


            float xInterval = 100; // 水印之间的水平间隔
            float yInterval = 100; // 水印之间的垂直间隔

            // Y坐标为0,沿X轴每间隔100生成水印信息
            for (float x = 0; x < pageSize.getWidth(); x = x + xInterval) {
                ColumnText.showTextAligned(content,
                        Element.ALIGN_CENTER, new Phrase(info, font),
                        x, 0, 45);
            }

            // X坐标为0,沿Y轴每间隔100生成水印信息
            for (float y = 100; y < pageSize.getHeight(); y = y + xInterval) {
                ColumnText.showTextAligned(content,
                        Element.ALIGN_CENTER, new Phrase(info, font),
                        0, y, 45);
            }

        }
    }

}

你可能感兴趣的:(java,pdf,开发语言)