笔记

万物寻其根,通其堵,便能解其困。
  博客园  :: 新随笔  :: 管理

写pdf

Posted on 2025-02-08 11:09  草妖  阅读(6)  评论(0)    收藏  举报

一、通过pdfbox进行写pdf

<dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox</artifactId>
            <version>3.0.4</version>
        </dependency>

 

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.font.Standard14Fonts;

    public void tempAAAA(){
try{
    int pageIndex=0;  // 当前页下标
    PDDocument document = new PDDocument();
    PDPage page = new PDPage(PDRectangle.A4);
    document.addPage(page);
    final float pageWidth=page.getMediaBox().getWidth();
    final float pageHeight=page.getMediaBox().getHeight();
    PDPageContentStream contentStream = new PDPageContentStream(document, page);
    try{
       PDFont tempPDTFont=new PDType1Font(Standard14Fonts.FontName.HELVETICA);
       contentStream.setFont(tempPDTFont, 12);
    }catch (Exception ignored){}
    contentStream.beginText();
    // 其实坐标(0,0)表示左下角那个点
    contentStream.newLineAtOffset(50, pageHeight-30);
    //contentStream.showText("In the modern society study English is becoming more important and popular.");

    // 添加注释块
    PDAnnotationText textAnnotation = new PDAnnotationText();
    textAnnotation.setContents("In the modern society study English is becoming more important and popular.  With my mother and teacher’s encouragement and teaching, I studied very hard and won many prize in the competition. When I was in grade four, I passed PETS 1 with the score of 88 of writing, and 5 of oral English, and I passed PETS 2 in grade five. I was very happy and excited because I had the experience of talking with foreigners, and even used English to help some people when they met the communication problem. I was also very proud when the foreign people prized me that my English was good.Up till now, I have been studied English for about 6 years. I deeply realize the importance of learning English. I will continue to study in the future, and I really appreciate my mother and my English teacher,too. This year Beijing will host the 2008 Olympic games, I believe that master English well will certain help me to do some useful work for this Olym.");
    textAnnotation.setRectangle(new PDRectangle(100, 650, 200, 150)); // 设置注释位置和大小
    page.getAnnotations().add(textAnnotation);

    contentStream.endText();
    contentStream.close();
    File directory = new File("src/main/resources");
    String resource =null;
    try{
       // 线上环境
       resource=ResourceUtils.getURL("classpath:").getPath();  // 获取当前服务器的路径,并指定到指定的路径下
    }catch (Exception ignored){
       try {
          // 线上环境
          resource = Objects.requireNonNull(Objects.requireNonNull(ClassUtils.getDefaultClassLoader()).getResource(".")).getPath();
       }
       catch(Exception ignored1) {
          // 本地调试
          resource = directory.getCanonicalPath();
       }
    }
    if(resource.startsWith("/")){
       resource=resource.substring(1);
    }
    resource=resource.replace("\\", "/")+"META-INF/resources/stuExportFile/";
    File checkFileExists=new File(resource);
    if(!checkFileExists.exists()){
       checkFileExists.mkdirs();
    }
    resource+="HelloPDFBox.pdf";
    System.out.println(resource);
    document.save(resource);
} catch (Exception terr) {
    loggerService.writeInfo(Thread.currentThread().getStackTrace()[1].getMethodName() + "构建pdf失败()", terr);
}
 }

  

二、 通过itextpdf/html进行写pdf

<!-- 导出pdf添加 -->
        <!-- itextpdf依赖 -->
        <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcprov-jdk15to18</artifactId>
            <version>1.81</version>
        </dependency>
        <!-- 导出pdf -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.13.4</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf.tool</groupId>
            <artifactId>xmlworker</artifactId>
            <version>5.5.13.4</version>
        </dependency>
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.39</version>
        </dependency>
package ServiceImpl;

import base.CustomFontProvider;
import base.PdfHeaderFooter;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.charset.Charset;


/** 导出pdf处理
 * */
public class ExportPDFServiceImpl {
    private String quesAsk="time flies! i've been here for nearly a year. i'm very pleased to find that our school is really a good one. the students in our school__________________________________________________________________________";
    private String quesAnswer=" dear mum and dad, time flies! i've been here for nearly a year. i'm very pleased to find that our school is really a good one. the students in our school work hard at their lessons. they take an active part in activities that help to improve their qualities and health. they are friendly to each other and always ready to help each other. the teachers here all enjoy their work and they love their students. they work hard and do what they can do to help their students. and the students respect their teachers. they get on well with each other. the students in our school try their best to kkp the school yard clean.In the modern society study English is becoming more important and popular. But when I was young, I didn’t know of this and prefer to play outside rather than learn English. But my mother said :“English is the necessary tools to talk with foreigners, so you should study in an English class. Believeyourself, You can certainly study English well!”Finally I agreed my mom’s opinion and began to study ladder English when I was five.\n" +
            "\n" +
            "At the beginning I was happy to study, because it was fun in the English class. We played games, and only studied five words, sentence a time. We also learned to sing a lot of English songs. In this studying environment, I was interested in English for the first time.\n" +
            "\n" +
            "When I was in grade two, my mother thought that I should study English formally, so she let me study in the class of teacher Ye of Young Palace of Beijing. In her class I began to learn the New Concept English and touched the grammar for the first time. Teacher Ye let us practice the oral English, listening and writing. Although I should remember much more words than before and had to practice listening and writing every day, and must take the crowded bus to school for two hours every week, I was very happy because I could learn much knowledge that not taught in school.\n" +
            "\n" +
            "With my mother and teacher’s encouragement and teaching, I studied very hard and won many prize in the competition. When I was in grade four, I passed PETS 1 with the score of 88 of writing, and 5 of oral English, and I passed PETS 2 in grade five. I was very happy and excited because I had the experience of talking with foreigners, and even used English to help some people when they met the communication problem. I was also very proud when the foreign people prized me that my English was good.\n" +
            "\n" +
            "Up till now, I have been studied English for about 6 years. I deeply realize the importance of learning English. I will continue to study in the future, and I really appreciate my mother and my English teacher,too. This year Beijing will host the 2008 Olympic games, I believe that master English well will certain help me to do some useful work for this Olympics.";

    /** 通过itextpdf进行打印字符串
     * 备注:1、通过"\n"可以进行换行,但是"\r\t"不管用。 */
    public void exportPDFByItextPDF() throws Exception{
        String pathPathUrl=getClass().getResource("/").getPath() + "ExportPDF/";  // pdf文件路径
        File tempPathFile=new File(pathPathUrl);
        if(!tempPathFile.exists()){
            tempPathFile.mkdirs();
        }
        pathPathUrl+="1.pdf";
        // 页面大小
        Rectangle rect = new Rectangle(PageSize.B5.rotate());
        //页面背景色
        rect.setBackgroundColor(BaseColor.ORANGE);
        Document document = new Document(rect);
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pathPathUrl));
        //PDF版本(默认1.4)
        writer.setPdfVersion(PdfWriter.PDF_VERSION_1_2);
        // 设置密码为:"World"
        writer.setEncryption("Hello".getBytes(), "World".getBytes(),
                PdfWriter.ALLOW_SCREENREADERS,
                PdfWriter.STANDARD_ENCRYPTION_128);
        //文档属性
        document.addTitle("Title@sample");
        document.addAuthor("Author@rensanning");
        document.addSubject("Subject@iText sample");
        document.addKeywords("Keywords@iText");
        document.addCreator("Creator@iText");
        //页边空白
        document.setMargins(10, 20, 30, 40);
        document.open();

        document.add(new Paragraph(quesAnswer));

        /* 首行缩进
        Paragraph para = new Paragraph();
        para.setFirstLineIndent(50); // 设置左缩进为50单位(通常是1/72英寸)
        para.add(quesAnswer);
        document.add(para);
        */

        /* 整体缩进
        Paragraph para = new Paragraph();
        para.setIndentationLeft(50); // 设置左缩进为50单位(通常是1/72英寸)
        para.add(quesAnswer);
        document.add(para);
        */
        /* 设置列表整体的左缩进
        List list = new List(List.UNORDERED); // 或者使用 List(List.ORDERED) 创建有序列表
        list.setIndentationLeft(50); // 设置列表整体的左缩进
        list.add(new ListItem("dear mum and dad, time flies! i've been here for nearly a year. i'm very pleased to find that our school is really a good one. the students in our school work hard at their lessons. they take an active part in activities that help to improve their qualities and health. they are friendly to each other and always ready to help each other. the teachers here all enjoy their work and they love their students. they work hard and do what they can do to help their students. and the students respect their teachers. they get on well with each other. the students in our school try their best to kkp the school yard clean.In the modern society study English is becoming more important and popular. But when I was young, I didn’t know of this and prefer to play outside rather than learn English. But my mother said :“English is the necessary tools to talk with foreigners, so you should study in an English class. Believeyourself, You can certainly study English well!”Finally I agreed my mom’s opinion and began to study ladder English when I was five."));
        list.add(new ListItem("At the beginning I was happy to study, because it was fun in the English class. We played games, and only studied five words, sentence a time. We also learned to sing a lot of English songs. In this studying environment, I was interested in English for the first time."));
        document.add(list);
        */

        /*
        PdfPTable table = new PdfPTable(1); // 创建一个单列表格,列数为1
        PdfPCell cell = new PdfPCell(new Paragraph("带有缩进的单元格内容"));
        cell.setPaddingLeft(20); // 设置单元格内容的左填充,实现视觉上的缩进效果
        table.addCell(cell); // 添加单元格到表格中
        document.add(table); // 将表格添加到文档中
        */

        document.close();
        System.out.println("保存路径:"+pathPathUrl);
    }

    /** 通过itextpdf进行打印HTML文件
     * 参照:https://blog.csdn.net/z1353095373/article/details/124762949
     * */
    public void exportPDFOfHTMLByItextPDF() throws Exception{
        String targetPathUrl=getClass().getResource("/").getPath() + "ExportPDF/1.html";  // html文件
        String pathPathUrl=getClass().getResource("/").getPath() + "ExportPDF/";  // pdf文件路径
        File tempPathFile=new File(pathPathUrl);
        if(!tempPathFile.exists()){
            tempPathFile.mkdirs();
        }
        pathPathUrl+="html.pdf";
        // 第 1 步,创建一个 iTextSharp.text.Document 对象的实例:A4并设置边距
        Document document = new Document(PageSize.A4, 10, 20, 60, 80);
        // PDF属性(可写可不写)
        // document.addAuthor("author");// 作者
        // document.addTitle("title");// 标题
        // document.addSubject("subject");// 主题
        // document.addKeywords("keywords");// 关键字
        // 第 2 步,为该 Document 创建一个 Writer 实例:
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pathPathUrl));
        writer.setPageEvent(new PdfHeaderFooter());// 页眉页脚
        // 第 3 步,打开当前 Document
        document.open();
        // 第 4 步,为当前 Document 添加内容

        // 4.1 该为加载 html 文件字符串生成pdf方式
        // File file2 = ResourceUtils.getFile("D:\\test\\HelloWorld.html");
        // String s = FileReader.create(file2).readString();
        // ByteArrayInputStream fis = new ByteArrayInputStream(s.getBytes());

        // 4.2 该为加载 html 文件生成 pdf 方式
        FileInputStream fis = new FileInputStream(targetPathUrl);
        XMLWorkerHelper.getInstance().parseXHtml(writer, document, fis, null, Charset.defaultCharset(), new CustomFontProvider());

        // 第 5 步,关闭 Document
        document.close();
        System.out.println("保存路径:"+pathPathUrl);
    }
}