说明

这里需要下载一个字体文件,代码中的/root/simsun.ttc是字体文件,需要提前下载好,并放在指定的目录,这里的/root/simsun.ttc是字体文件的路径,需要根据实际情况进行修改。
下载地址:https://github.com/jiaxiaochu/font/blob/master/simsun.ttc

引入依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox-tools</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>net.sf.cssbox</groupId>
<artifactId>pdf2dom</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.10</version>
</dependency>
<dependency>
<groupId>com.itextpdf.tool</groupId>
<artifactId>xmlworker</artifactId>
<version>5.5.10</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.15</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>3.15</version>
</dependency>

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51

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

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;

/**
* PdfUtil Pdf文件工具
*
* @author zq
* @version 2024/09/26 22:
**/
public class PdfUtil {
public static void createPdf(String content, String pdfPath) throws IOException, DocumentException {
Document pdfDoc = new Document(PageSize.A4);
PdfWriter.getInstance(pdfDoc, new FileOutputStream(pdfPath))
.setPdfVersion(PdfWriter.PDF_VERSION_1_7);
pdfDoc.open();
BaseFont bfChinese = BaseFont.createFont("/root/simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Font myfont = new Font(bfChinese, 11, Font.NORMAL);
pdfDoc.add(new Paragraph("\n"));
Paragraph para = new Paragraph(content + "\n", myfont);
para.setAlignment(Element.ALIGN_JUSTIFIED);
pdfDoc.add(para);
pdfDoc.close();
}

public static void txt2pdf(String txtPath, String pdfPath) throws IOException, DocumentException {
Document pdfDoc = new Document(PageSize.A4);
PdfWriter.getInstance(pdfDoc, new FileOutputStream(pdfPath))
.setPdfVersion(PdfWriter.PDF_VERSION_1_7);
pdfDoc.open();
BaseFont bfChinese = BaseFont.createFont("/root/simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Font myfont = new Font(bfChinese, 11, Font.NORMAL);
pdfDoc.add(new Paragraph("\n"));
BufferedReader br = new BufferedReader(new FileReader(txtPath));
String strLine;
while ((strLine = br.readLine()) != null) {
Paragraph para = new Paragraph(strLine + "\n", myfont);
para.setAlignment(Element.ALIGN_JUSTIFIED);
pdfDoc.add(para);
}
pdfDoc.close();
br.close();

}
}