SpringBoot-iText-Pdf

x33g5p2x  于2021-09-22 转载在 Spring  
字(62.7k)|赞(0)|评价(0)|浏览(889)

SpringBoot-iText-Pdf

需要的全部Maven

  1. <parent>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-parent</artifactId>
  4. <version>2.0.6.RELEASE</version>
  5. </parent>
  6. <properties>
  7. <maven.compiler.source>8</maven.compiler.source>
  8. <maven.compiler.target>8</maven.compiler.target>
  9. </properties>
  10. <dependencies>
  11. <dependency>
  12. <groupId>org.springframework.boot</groupId>
  13. <artifactId>spring-boot-starter-web</artifactId>
  14. </dependency>
  15. <!-- itextpdf -->
  16. <dependency>
  17. <groupId>com.itextpdf</groupId>
  18. <artifactId>itextpdf</artifactId>
  19. <version>5.5.11</version>
  20. </dependency>
  21. <!-- itext水印-->
  22. <dependency>
  23. <groupId>org.bouncycastle</groupId>
  24. <artifactId>bcprov-jdk15on</artifactId>
  25. <version>1.47</version>
  26. </dependency>
  27. <dependency>
  28. <groupId>org.bouncycastle</groupId>
  29. <artifactId>bcmail-jdk15on</artifactId>
  30. <version>1.47</version>
  31. </dependency>
  32. <dependency>
  33. <groupId>com.itextpdf</groupId>
  34. <artifactId>itext-asian</artifactId>
  35. <version>5.2.0</version>
  36. </dependency>
  37. <dependency>
  38. <groupId>org.xhtmlrenderer</groupId>
  39. <artifactId>core-renderer</artifactId>
  40. <version>R8</version>
  41. </dependency>
  42. <dependency>
  43. <groupId>org.apache.commons</groupId>
  44. <artifactId>commons-io</artifactId>
  45. <version>1.3.2</version>
  46. </dependency>
  47. <dependency>
  48. <groupId>org.freemarker</groupId>
  49. <artifactId>freemarker</artifactId>
  50. <version>2.3.28</version>
  51. </dependency>
  52. <!-- 渲染 css 样式 -->
  53. <dependency>
  54. <groupId>org.xhtmlrenderer</groupId>
  55. <artifactId>flying-saucer-pdf</artifactId>
  56. <version>9.1.16</version>
  57. </dependency>
  58. <dependency>
  59. <groupId>org.projectlombok</groupId>
  60. <artifactId>lombok</artifactId>
  61. </dependency>
  62. <dependency>
  63. <groupId>org.jsoup</groupId>
  64. <artifactId>jsoup</artifactId>
  65. <version>1.11.3</version>
  66. </dependency>
  67. <dependency>
  68. <groupId>org.apache.commons</groupId>
  69. <artifactId>commons-lang3</artifactId>
  70. <version>3.11</version>
  71. </dependency>
  72. </dependencies>

生成一个PDF

需要5个步骤

创建文档

  1. Document document = new Document();

生成PDF

  1. PdfWriter.getInstance(doc, new FileOutputStream(DEST+ File.separator+"HelloWorld.pdf") );

打开PDF

  1. document.open();

往PDF中写入内容

  1. document.add(new Paragraph("Hello World"));

关闭PDF

  1. document.close();

完整版

  1. Document doc = new Document();
  2. PdfWriter.getInstance(doc, new FileOutputStream(FILE_DIR +"createSamplePDF.pdf"));
  3. doc.open();
  4. doc.add(new Paragraph("Hello World"));
  5. doc.close();

必须知道的内容

在操作演示PDF前我们需要知道如何获取 classes目录的路径 (项目打包后的根路径)

只有这样我们生成的PDF会在项目内部(当然如果你不需要PDF在项目的classes目录而且在其他地方,自行补充路径)

  1. private static String FILE_DIR = null;
  2. static {
  3. try {
  4. FILE_DIR = Paths.get(ResourceUtils.getURL("classpath:").getPath().substring(1)).toString()+ File.separator;
  5. } catch (FileNotFoundException e) {
  6. e.printStackTrace();
  7. }
  8. }

我们还需要知道一个问题就是itext默认不支持中文(默认隐藏中文字体只显示英文)

我们可以在添加中文时候的那个对象中(基本都有设置字体格式的方法) 添加下面方法,就能识别中文了
对象.setFont(PdfUtils.getChineseFont());

在块.短语,段落,的构造第二个参数是可以直接添加PdfUtils.getChineseFont()

中文字体工具类

  1. package com.pdf.utils;
  2. import com.itextpdf.text.BaseColor;
  3. import com.itextpdf.text.DocumentException;
  4. import com.itextpdf.text.Font;
  5. import com.itextpdf.text.pdf.BaseFont;
  6. import java.io.IOException;
  7. public class PdfFont {
  8. // color= BaseColor.BLUE(蓝色) BaseColor.BLACK(黑色) new BaseColor(105, 105, 105)(文本色)
  9. // style= Font.ITALIC细,Font.NORMA正常L,Font.BOLD粗
  10. // size=字体大小
  11. public static Font getChineseFont( int size,int style,BaseColor color) {
  12. BaseFont bfChinese;
  13. Font fontChinese = null;
  14. try {
  15. bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
  16. fontChinese = new Font(bfChinese, size, style, color);
  17. } catch (DocumentException e) {
  18. e.printStackTrace();
  19. } catch (IOException e) {
  20. e.printStackTrace();
  21. }
  22. return fontChinese;
  23. }
  24. public static Font getChineseFont(int size, int style) {
  25. BaseFont bfChinese;
  26. Font fontChinese = null;
  27. try {
  28. bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
  29. fontChinese = new Font(bfChinese, size, style, new BaseColor(105, 105, 105));
  30. } catch (DocumentException e) {
  31. e.printStackTrace();
  32. } catch (IOException e) {
  33. e.printStackTrace();
  34. }
  35. return fontChinese;
  36. }
  37. public static Font getChineseFont( int size) {
  38. BaseFont bfChinese;
  39. Font fontChinese = null;
  40. try {
  41. bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
  42. fontChinese = new Font(bfChinese, size, Font.NORMAL, new BaseColor(105, 105, 105));
  43. } catch (DocumentException e) {
  44. e.printStackTrace();
  45. } catch (IOException e) {
  46. e.printStackTrace();
  47. }
  48. return fontChinese;
  49. }
  50. public static Font getChineseFont(int style,BaseColor color) {
  51. BaseFont bfChinese;
  52. Font fontChinese = null;
  53. try {
  54. bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
  55. fontChinese = new Font(bfChinese,style, Font.NORMAL, color);
  56. } catch (DocumentException e) {
  57. e.printStackTrace();
  58. } catch (IOException e) {
  59. e.printStackTrace();
  60. }
  61. return fontChinese;
  62. }
  63. public static Font getChineseFont( long size, BaseColor color) {
  64. BaseFont bfChinese;
  65. Font fontChinese = null;
  66. try {
  67. bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
  68. fontChinese = new Font(bfChinese, size, Font.NORMAL, color);
  69. } catch (DocumentException e) {
  70. e.printStackTrace();
  71. } catch (IOException e) {
  72. e.printStackTrace();
  73. }
  74. return fontChinese;
  75. }
  76. public static Font getChineseFont( BaseColor color) {
  77. BaseFont bfChinese;
  78. Font fontChinese = null;
  79. try {
  80. bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
  81. fontChinese = new Font(bfChinese, 15, Font.NORMAL, color);
  82. } catch (DocumentException e) {
  83. e.printStackTrace();
  84. } catch (IOException e) {
  85. e.printStackTrace();
  86. }
  87. return fontChinese;
  88. }
  89. // 默认配置 黑色字体 大小15 不加粗
  90. public static Font getChineseFont( ) {
  91. BaseFont bfChinese;
  92. Font fontChinese = null;
  93. try {
  94. bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
  95. fontChinese = new Font(bfChinese, 15, Font.NORMAL, new BaseColor(105, 105, 105));
  96. } catch (DocumentException e) {
  97. e.printStackTrace();
  98. } catch (IOException e) {
  99. e.printStackTrace();
  100. }
  101. return fontChinese;
  102. }
  103. }

PDF基础配置

需要倒入的包

  1. import com.itextpdf.text.*;
  2. import com.itextpdf.text.Font;
  3. import com.itextpdf.text.Image;
  4. import com.itextpdf.text.List;
  5. import com.itextpdf.text.Rectangle;
  6. import com.itextpdf.text.pdf.*;
  7. import com.itextpdf.text.pdf.draw.DottedLineSeparator;
  8. import com.itextpdf.text.pdf.draw.LineSeparator;
  9. import com.itextpdf.text.pdf.draw.VerticalPositionMark;
  10. import lombok.SneakyThrows;
  11. import org.junit.Test;
  12. import org.springframework.util.ResourceUtils;
  13. import java.awt.*;
  14. import java.io.*;
  15. import java.nio.file.Paths;
  16. import java.util.ArrayList;
  17. import java.util.Iterator;
  18. import java.util.zip.ZipEntry;
  19. import java.util.zip.ZipOutputStream;

注意:看每个配置 哪行代码的后面 如果顺序错了那么久无效了

配置PDF

页面大小

  1. Rectangle rect = new Rectangle(PageSize.B4.rotate());
  2. Document doc = new Document(rect);

不止B4你进入PageSize类里有一大堆 常用B4

比如:

  1. B5 ,B6 B 7 这些都是比B4小
  2. B3, B2 都是比B4大

页面背景

不设置默认为白色

  1. Rectangle rect = new Rectangle(PageSize.B4.rotate());
  2. rect.setBackgroundColor(new BaseColor(199 , 237, 204) ); //设置颜色
  3. Document doc = new Document(rect);

推荐几款护眼的颜色:

new BaseColor(199 , 237, 204) 豆沙绿(推荐)

new BaseColor(200, 200, 169) 淡青色

new BaseColor(254, 67, 101) 淡红色

new BaseColor(252, 167, 154) 淡粉色

new BaseColor(249, 205, 173) 淡黄色
1.
PDF版本设置(默认1.4)

  1. PdfWriter writer = PdfWriter.getInstance(xxxxxx);
  2. writer.setPdfVersion(PdfWriter.PDF_VERSION_1_2); //设置版本号 一般不设置默认就可以

PDF文档属性(Title,Author,Subject,Keywords )

  1. Document doc = new Document();
  2. PdfWriter writer = PdfWriter.getInstance(xxxxxx);
  3. //文档属性 注意: 如果设置了版本号那么需要在版本号后面写
  4. doc.addTitle("标题");
  5. doc.addAuthor("作者");
  6. doc.addSubject("主题");
  7. doc.addKeywords("关键字");
  8. doc.addCreator("创建者");

文档属性可以有可无 看你心情

页边空白

  1. Document doc = new Document();
  2. PdfWriter writer = PdfWriter.getInstance(xxxxxx);//必须在这行后面
  3. doc.setMargins(10, 20, 30, 40); //页边空白 左 右 上 下

配置后的效果

PDF密码

就相当于给文件加密需要使用密码验证后才能观看

  1. Document doc = new Document();
  2. PdfWriter writer = PdfWriter.getInstance(xxxxxx);//必须在这行后面
  3. // 设置密码
  4. //第一个参数是用户密码(允许复制,签名 不允许打印,编辑)
  5. //第二个参数是管理员密码(允许打印,编辑,复制,签名 加密级别)
  6. writer.setEncryption("user".getBytes(), "admin".getBytes(),
  7. PdfWriter.ALLOW_COPY, // 允许复制,签名 不允许打印,编辑
  8. PdfWriter.STANDARD_ENCRYPTION_128); //允许打印,编辑,复制,签名 加密级别

增删page(页)

添加PDF页 看代码你就懂了

  1. Rectangle rect = new Rectangle(PageSize.B4.rotate());
  2. Document doc = new Document(rect);
  3. PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(FILE_DIR + "createSamplePDF.pdf"));
  4. doc.open(); //打开PDF 默认为第一页
  5. doc.add(new Paragraph("First page")); // 给第一个添加内容
  6. doc.add(new Paragraph("Hello World"));
  7. doc.newPage(); // 创建第2页
  8. writer.setPageEmpty(false); //可以允许第2页为空 如果不设置那么PDF默认给没有内容的页 取消掉
  9. doc.newPage(); // 创建第3页
  10. doc.add(new Paragraph("New page"));
  11. doc.close();

//删除PDF页 // 看代码你就懂了

只选择指定类其他的删除

  1. PdfReader reader = new PdfReader(FILE_DIR + "createSamplePDF.pdf");
  2. // 从原PDF中抽取指定页 生成
  3. reader.selectPages("1,3,5"); //只选择1和3页和第5页
  4. //生成新的PDF
  5. PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(FILE_DIR
  6. + "createSamplePDF_de.pdf"));
  7. stamp.close();
  8. reader.close();

只选择指定范围页其他页删除

  1. /** * 截取pdfFile的第from页至第end页,组成一个新的文件名 * @param respdfFile 需要分割的PDF * @param savepath 新PDF * @param from 起始页 * @param end 结束页 */
  2. public static void splitPDFFile(String respdfFile, String savepath, int from, int end) {
  3. Document document = null;
  4. PdfCopy copy = null;
  5. try {
  6. PdfReader reader = new PdfReader(respdfFile);
  7. int n = reader.getNumberOfPages();
  8. if(end==0){
  9. end = n;
  10. }
  11. ArrayList<String> savepaths = new ArrayList<String>();
  12. savepaths.add(savepath);
  13. document = new Document(reader.getPageSize(1));
  14. copy = new PdfCopy(document, new FileOutputStream(savepaths.get(0)));
  15. document.open();
  16. for(int j=from; j<=end; j++) {
  17. document.newPage();
  18. PdfImportedPage page = copy.getImportedPage(reader, j);
  19. copy.addPage(page);
  20. }
  21. document.close();
  22. } catch (IOException e) {
  23. e.printStackTrace();
  24. } catch(DocumentException e) {
  25. e.printStackTrace();
  26. }
  27. }

PDF内容

如果你对BaseFont类自带的字体颜色不满足的话我们可以自己进行配色

这个网站是rgb颜色表 http://www.wahart.com.hk/rgb.htm new BaseColor(r, g, b);

基础

Chunk(块)

Chunk : 块,PDF文档中描述的最小原子元素 ,其他高级的文本对象都是基于Chunk的

在水平方向,Chunk的字符满一行,就会从头开始。请注意,这是从头开始,而不是另起一行。对于Chunk来说,行间距默认为0,那么当文档中只有Chunk时,这些字符永远只会出现再第一行。

注意:块一般不会单独使用而且和其他文本对象进行组合使用的

  1. doc.open(); //打开PDF 默认为第一页
  2. //定义一个块
  3. Chunk chunk = new Chunk("Cat");
  4. //设置块的背景色 (可选)
  5. // chunk.setBackground(BaseColor.WHITE); //白色背景(默认)
  6. //设置快内的字体为可识别中文字体
  7. //字体样式,编码格式,插入方式,字体大小,字体样式(Font.ITALIC细,Font.NORMA正常L,Font.BOLD粗),字体颜色)
  8. Font font = FontFactory.getFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED,17, Font.NORMAL, new BaseColor(105, 105, 105));
  9. //设置快内的字体颜色
  10. chunk.setFont(font);
  11. //增加块到文档
  12. doc.add(chunk);
  13. doc.close();

如果单独使用块的话-块重叠案例

  1. doc.open(); //打开PDF 默认为第一页
  2. //建块
  3. int i=0;
  4. for(i=1; i<=11; i++){
  5. doc.add(new Chunk("This is sentence "+i+". "));
  6. }
  7. doc.close();

可以发现重叠了 ,所以块一般是不能单独使用的,我们要配合下面的更高级文本对象进行使用,进行改变一条句子中的某些字的样式

Phrase(短句)

Phrase作用是添加一个短句。短语类知道如何添加行与行之间的间距。 但是没法和Chunk一样设置样式

  1. doc.open(); //打开PDF 默认为第一页
  2. //添加短句
  3. int i=0;
  4. for(i=1; i<11; i++){
  5. doc.add(new Phrase("This is sentence "+i+". "));
  6. }
  7. doc.close();

可以看到了和Chunk不同的是,会自动换行了,既然Chunk可以 设置样式Phrase可以自动换行那么我们将他们组合不就可以了

Phrase组合Chunk使用

  1. doc.open(); //打开PDF 默认为第一页
  2. //定义一个块
  3. Chunk chunk1 = new Chunk("哈哈哈哈哈哈1");
  4. //添加横线 比如下划线(0.2f, -2f) 删除线(0.2f, 4f) 第一个参数是浓度 ,第二个参数是位置 横线位置
  5. chunk1.setUnderline(0.2f, 4f);
  6. Font font1 = FontFactory.getFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED,17, Font.NORMAL, new BaseColor(105, 105, 105));
  7. chunk1.setFont(font1);
  8. Chunk chunk2 = new Chunk("惺惺惜惺惺想寻2");
  9. chunk2.setBackground(new BaseColor(200, 200, 169) );//添加块背景颜色
  10. Font font2 = FontFactory.getFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED,22, Font.NORMAL, new BaseColor(105, 105, 105));
  11. chunk2.setFont(font2);
  12. //将块添加到短句里
  13. Phrase elements = new Phrase(50); //设置行间距
  14. elements.add(chunk1);
  15. elements.add(chunk2);
  16. doc.add(elements);
  17. doc.close();

这样Phrase就能有Chunk的样式效果了

  1. doc.open(); //打开PDF 默认为第一页
  2. //定义段落
  3. Paragraph paragraph = new Paragraph();
  4. //插入十条文本块到段落中
  5. int i=0;
  6. for(i=0; i<10; i++){
  7. Chunk chunk = new Chunk("This is a sentence which is long " + i + ". ");
  8. paragraph.add(chunk);
  9. }
  10. //添加段落
  11. doc.add(paragraph);
  12. doc.close();
Paragraph(段落)

Paragraph 是段落的处理。在一个段落中 每一个段落都会结尾自带换行,

你可以设置段落的对齐方式,缩进和间距。 简单来说就是对Phrase进行升级了

可以操控文本在PDF中的位置了

  1. doc.open(); //打开PDF 默认为第一页
  2. //定义段落
  3. Paragraph paragraph = new Paragraph();
  4. //插入10条文本块到段落中
  5. int i=0;
  6. for(i=0; i<10; i++){
  7. Chunk chunk = new Chunk("This is a sentence which is long " + i + ". ");
  8. paragraph.add(chunk);
  9. }
  10. doc.add(paragraph);
  11. doc.close();

暂时看来和短句的运行效果差不多,每句都在自己的行。

您可以设置一个段落前后的间距。 也就是行的上间距和下间距

  1. paragraph.setSpacingAfter(50);
  2. paragraph.setSpacingBefore(50);

您可以设置使用setAlignment()方法的段落的对齐方式。

  1. paragraph.setAlignment(Element.ALIGN_LEFT); //靠左
  2. paragraph.setAlignment(Element.ALIGN_CENTER); //居中
  3. paragraph.setAlignment(Element.ALIGN_RIGHT); //靠右

您可以设置该段左,右缩进。

  1. paragraph.setIndentationLeft(50);
  2. paragraph.setIndentationRight(50);

案例演示

  1. doc.open(); //打开PDF 默认为第一页
  2. //定义段落1
  3. Paragraph paragraph = new Paragraph("This is a sentence which is long . ");
  4. //设置段段落居中
  5. paragraph.setAlignment(Element.ALIGN_CENTER);
  6. //设置段落行缩进
  7. paragraph.setIndentationLeft(10); //左边缩进
  8. //添加段落
  9. doc.add(paragraph);
  10. //定义段落2
  11. Paragraph paragraph1 = new Paragraph("This is a sentence which is long . ");
  12. //设置段落行的上间距
  13. paragraph1.setSpacingAfter(20);
  14. //设置段段落居中
  15. paragraph1.setAlignment(Element.ALIGN_CENTER);
  16. //设置段落行缩进
  17. paragraph1.setIndentationLeft(150); //左边缩进
  18. //添加段落
  19. doc.add(paragraph1);
  20. doc.close();

拿什么时候使用Chunk 什么时候使用Phrase 什么时候使用Paragraph呢?

Chunk: 只能设置字体和背景样式 ,而且内容只能在一行中

Phrase: 行满自动换行,可以设置行高, 但是不能手动换行,不能设置字体样式

Paragraph: 除了不能设置字体样式和背景外 基本文本所能用于的特性都可以实现 ,每个Paragraph结尾自带换行

通俗易懂的话来讲就是 Paragraph用来设置内容排版 Phrase用来拼接语句的, Chunk用来设置字体和背景样式的

操作字的位置透明旋转…
  1. PdfWriter instance = PdfWriter.getInstance(doc, new FileOutputStream(FILE_DIR + "createSamplePDF.pdf"));
  2. doc.open(); //打开PDF 默认为第一页
  3. PdfGState gs = new PdfGState();
  4. gs.setFillOpacity(0.3f);//透明度
  5. PdfContentByte canvas = instance.getDirectContent();
  6. canvas.setGState(gs);
  7. Phrase phrase1 = new Phrase("This is a test!left");
  8. Phrase phrase2 = new Phrase("This is a test!right");
  9. Phrase phrase3 = new Phrase("This is a test!center");
  10. // 参数1 默认就行 ,参数2默认就行,参数3内容,参数4x轴,参数5y轴,参数6字体旋转
  11. ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, phrase1, 100, 500, 10);
  12. ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, phrase2, 150, 536, 40);
  13. ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, phrase3, 200, 572, 60);
  14. doc.close();

注意 :起始位置是左上角 x 是正数=往右 y是正数=往上 否则反之

List(列表)

有序列表 无需列表 字母列表
注意导包 import com.itextpdf.text./*; 而不是java.util

有序列表

  1. doc.open(); //打开PDF 默认为第一页
  2. List orderedList = new List(List.ORDERED);
  3. for (int i = 0; i < 10; i++) {
  4. orderedList.add(new ListItem("Item "));
  5. }
  6. doc.add(orderedList);
  7. doc.close();

无序列表

  1. doc.open(); //打开PDF 默认为第一页
  2. List unorderedList = new List(List.UNORDERED);
  3. for (int i = 0; i < 10; i++) {
  4. unorderedList.add(new ListItem("Item "));
  5. }
  6. doc.add(unorderedList);
  7. doc.close();

手指列表

  1. doc.open(); //打开PDF 默认为第一页
  2. ZapfDingbatsList zapfDingbatsList = new ZapfDingbatsList(43, 30);
  3. for (int i = 0; i < 10; i++) {
  4. zapfDingbatsList.add(new ListItem("Item "));
  5. }
  6. doc.add(zapfDingbatsList);

列表嵌套

  1. doc.open(); //打开PDF 默认为第一页
  2. // 父列表
  3. List orderedList = new List(List.ORDERED);
  4. orderedList.add(new ListItem("Item "));
  5. // 子列表
  6. List unorderedList = new List(false, false, 30);
  7. for (int i = 0; i < 5; i++) {
  8. //取消列表符合
  9. unorderedList.setListSymbol(new Chunk("", FontFactory.getFont(FontFactory.HELVETICA, 6)));
  10. unorderedList.add(new ListItem("Item"));
  11. }
  12. orderedList.add(unorderedList);
  13. doc.add(orderedList);
  14. doc.close();

高级

Anchor(链接)

Anchor,相当于html中的超链接,主要实现2个功能:

1.跳转到外部站点。

2.跳转到文档的特定位置。

跳转到特定网站,只需要设置Anchor对象的Reference属性

调转到文档的特定位置(在HTML中是描点),先要创建一个Anchor对象到特定位置,并为其命名,如“China”,然后,在创建一个Anchor至于需要点击的位置,设置其Reference属性为“/#China”

演示一个锚链接

  1. doc.open(); //打开PDF 默认为第一页
  2. // Anchor超链接和锚点对象: internal and external links
  3. Anchor dest = new Anchor("连接到设置的UN锚点", PdfFont.getChineseFont(BaseColor.BLUE));
  4. dest.setName("CN"); // 设置锚点
  5. dest.setReference("#UN");// 跳转到UN锚点
  6. doc.add(dest);
  7. doc.newPage(); // 创建第2页
  8. instance.setPageEmpty(false); //可以允许第2页为空 如果不设置那么PDF默认给没有内容的页 取消掉
  9. doc.newPage(); // 创建第3页
  10. Anchor toUS = new Anchor("连接到设置的CN锚点。", PdfFont.getChineseFont(BaseColor.BLUE));
  11. toUS.setName("UN");
  12. toUS.setReference("#CN");// 跳转到CN锚点
  13. doc.add(toUS);
  14. doc.close();

锚链可以制作目录和导航

演示创建超链接跳转百度

  1. doc.open(); //打开PDF 默认为第一页
  2. Anchor dest = new Anchor("超链接", PdfFont.getChineseFont(BaseColor.BLUE));
  3. dest.setReference("http://www.baidu.com");// 如果不是描点,那么我们可以使用超链接连接
  4. doc.add(dest);
  5. doc.close();
Chapter(章) Section(节)
  1. doc.open(); //打开PDF 默认为第一页
  2. //定义段落
  3. Paragraph paragraph = new Paragraph();
  4. //添加段落内容
  5. paragraph.add(new Phrase("This is a chapter."));
  6. //定义章
  7. Chapter chapter = new Chapter(paragraph, 1);
  8. //添加章-节内容
  9. chapter.addSection("This is section 1", 2);
  10. chapter.addSection("This is section 2", 2);
  11. //添加章节
  12. doc.add(chapter);
  13. doc.close();

代码中chapter.addSection(“This is section 1”, 2)中的2是设置深度,如果设置成1跟章得头是一个级别了。

Image(图片)

如果同一个图像创建多次并都添加到文档中,文档的大小就增长很快,如果一个图像要在多个地方使用,只要生成一个Image对象,在添加到文档前,设置其属性就可以了,没有必要创建多份。

创建图像

  1. Image img = Image.getInstance(FILE_DIR+"baidu.jpg");
  2. doc.add(img);

图片的配置

  1. img.setBorder(Image.BOX) //边框,
  2. img.setBorderWidth(10)//边框宽度
  3. img.setBorderColor(BaseColor.WHITE) //边框颜色,
  4. img.setRotationDegrees(-30) //旋转 正向左旋转 负向右旋转
  5. img.setAbsolutePosition(x,y) //绝对位置 0,0 是最左下角 x变大向右移动 y变大向上移动

缩放图片

  1. img.scaleAbsolute(150, 150);//绝对宽和高
  2. img.scaleAbsoluteWidth(150);//绝对宽
  3. img.scaleAbsoluteHeight(150);//绝对高
  4. img.scalePercent(50); //百分比
  5. img.scaleToFit(400,300);//像素大小

对其方式

  1. img.setAlignment(Image.LEFT)
  2. // Image.LEFT(最左边) Image.RIGHT(最右边) Image.TOP(中)

图片自适应大小

  1. Rectangle rect = new Rectangle(PageSize.B4.rotate());
  2. Document doc = new Document(rect);
  3. PdfWriter instance = PdfWriter.getInstance(doc, new FileOutputStream(FILE_DIR + "splitPDF2.pdf"));
  4. doc.open(); //打开PDF 默认为第一页
  5. Image img = Image.getInstance(FILE_DIR+"37.jpg");
  6. img.scaleToFit(rect.getWidth(), rect.getHeight()); //关键代码
  7. doc.add(img);
  8. doc.close();

简单小演示

  1. doc.open(); //打开PDF 默认为第一页
  2. Paragraph paragraph = new Paragraph("你妹的", PdfFont.getChineseFont(BaseColor.BLACK));
  3. paragraph.setAlignment(Element.ALIGN_CENTER);
  4. doc.add(paragraph );
  5. //插入图片
  6. Image img = Image.getInstance(FILE_DIR+"baidu.jpg");
  7. img.setAlignment( Image.RIGHT); //图片靠右
  8. img.scaleToFit(200, 100);//大小
  9. img.setRotationDegrees(-30);//旋转
  10. doc.add(img);
  11. //定义段落
  12. Paragraph paragraph1 = new Paragraph("作者:xxxxxxxxx",PdfFont.getChineseFont(BaseColor.BLACK));
  13. paragraph1.setAlignment(Element.ALIGN_RIGHT);
  14. doc.add(paragraph1);
  15. doc.close();

分割线线条

箭头

  1. doc.open(); //打开PDF 默认为第一页
  2. doc.add(new VerticalPositionMark() {
  3. public void draw(PdfContentByte canvas, float llx, float lly,
  4. float urx, float ury, float y) {
  5. canvas.beginText();
  6. BaseFont bf = null;
  7. try {
  8. bf = BaseFont.createFont(BaseFont.ZAPFDINGBATS, "", BaseFont.EMBEDDED);
  9. } catch (Exception e) {
  10. e.printStackTrace();
  11. }
  12. canvas.setFontAndSize(bf, 12);
  13. // LEFT
  14. canvas.showTextAligned(Element.ALIGN_CENTER, String.valueOf((char) 220), llx - 10, y, 0);
  15. // RIGHT
  16. canvas.showTextAligned(Element.ALIGN_CENTER, String.valueOf((char) 220), urx + 10, y + 8, 180);
  17. canvas.endText();
  18. }
  19. });
  20. doc.close();

直线

  1. doc.open(); //打开PDF 默认为第一页
  2. Paragraph p1 = new Paragraph("LEFT");
  3. p1.add(new Chunk(new LineSeparator()));
  4. p1.add("RIGHT");
  5. doc.add(p1);
  6. doc.close();

点线

  1. Paragraph p1 = new Paragraph("LEFT");
  2. p1.add(new Chunk(new DottedLineSeparator()));
  3. p1.add("RIGHT");
  4. doc.add(p1);

下划线

  1. doc.open(); //打开PDF 默认为第一页
  2. LineSeparator UNDERLINE = new LineSeparator(1, 100, null, Element.ALIGN_CENTER, -2);
  3. Paragraph p3 = new Paragraph();
  4. p3.setFont(PdfFont.getChineseFont());//设置中文支撑
  5. p3.add("三生三世惺惺惜惺惺想寻寻寻寻寻寻寻寻寻寻寻寻寻");
  6. p3.add(UNDERLINE);//下划线
  7. p3.add("NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN");
  8. p3.add(UNDERLINE);//下划线
  9. doc.add(p3);
  10. doc.close();

https://www.cnblogs.com/liaojie970/p/7132475.html 设置段落位置

PDF转换

给PDF添加水印

分为图片水印和字体水印 因为有点复杂的缘故我直接封装好了工具类直接可以使用 ,但是也不是一成不变的,

需要你根据情况进行调整大小,一般默认配置就够用了

注意:设置水印和设置图片不是一个概念,如果PDF有背景颜色的话会将水印盖住这个需要注意 ,

因为水印是PDF文件生成好后,后期添加上去的,在堆层的最底层

PdfWatermark水印工具类

  1. package com.pdf.utils;
  2. import com.itextpdf.text.BaseColor;
  3. import com.itextpdf.text.DocumentException;
  4. import com.itextpdf.text.Element;
  5. import com.itextpdf.text.Image;
  6. import com.itextpdf.text.pdf.*;
  7. import java.io.BufferedOutputStream;
  8. import java.io.FileInputStream;
  9. import java.io.FileOutputStream;
  10. import java.io.IOException;
  11. public class PdfWatermark {
  12. /** * 文字水印 * <p> * 中间或者两边水印 * * @param bos 添加完水印的输出 * @param input 原PDF文件输入 * @param word 水印内容 * @param model 水印添加位置1中间,2两边 */
  13. public static void setWatermark(String bos, String input, String word, int model)
  14. throws DocumentException, IOException {
  15. PdfReader reader = new PdfReader(new FileInputStream(input));
  16. PdfStamper stamper = new PdfStamper(reader,new BufferedOutputStream(new FileOutputStream(bos) ));
  17. PdfContentByte content;
  18. // 创建字体,第一个参数是字体路径,itext有一些默认的字体比如说:
  19. BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
  20. PdfGState gs = new PdfGState();
  21. gs.setFillOpacity(0.3f);//水印透明度
  22. // 获取PDF页数
  23. int total = reader.getNumberOfPages();
  24. // 遍历每一页
  25. for (int i = 0; i < total; i++) {
  26. float width = reader.getPageSize(i + 1).getWidth(); // 页宽度
  27. float height = reader.getPageSize(i + 1).getHeight(); // 页高度
  28. content = stamper.getOverContent(i + 1);// 内容
  29. content.beginText();//开始写入文本
  30. content.setGState(gs);
  31. content.setColorFill(BaseColor.LIGHT_GRAY);
  32. content.setTextMatrix(70, 200);//设置字体的输出位置
  33. if (model == 1) { //平行居中的3条水印
  34. content.setFontAndSize(base, 40); //字体大小
  35. //showTextAligned 方法的参数分别是(文字对齐方式,位置内容,输出水印X轴位置,Y轴位置,旋转角度)
  36. content.showTextAligned(Element.ALIGN_CENTER, word, width / 2, height/3, 30);
  37. content.showTextAligned(Element.ALIGN_CENTER, word, width / 2, height/2, 30);
  38. content.showTextAligned(Element.ALIGN_CENTER, word, width / 2, height/4-50, 30);
  39. } else { // 左右两边个从上到下4条水印
  40. float rotation = 30;// 水印旋转度数
  41. content.setFontAndSize(base, 20);
  42. content.showTextAligned(Element.ALIGN_LEFT, word, 20, height - 50, rotation);
  43. content.showTextAligned(Element.ALIGN_LEFT, word, 20, height / 4 * 3 - 50, rotation);
  44. content.showTextAligned(Element.ALIGN_LEFT, word, 20, height / 2 - 50, rotation);
  45. content.showTextAligned(Element.ALIGN_LEFT, word, 20, height / 4 - 50, rotation);
  46. content.setFontAndSize(base, 22);
  47. content.showTextAligned(Element.ALIGN_RIGHT, word, width - 20, height - 50, rotation);
  48. content.showTextAligned(Element.ALIGN_RIGHT, word, width - 20, height / 4 * 3 - 50, rotation);
  49. content.showTextAligned(Element.ALIGN_RIGHT, word, width - 20, height / 2 - 50, rotation);
  50. content.showTextAligned(Element.ALIGN_RIGHT, word, width - 20, height / 4 - 50, rotation);
  51. }
  52. content.endText();//结束写入文本
  53. }
  54. stamper.close();
  55. reader.close();
  56. }
  57. /** * 给pdf文件添加水印 (注意如果有添加背景颜色的话那么 图片水印将失效被盖住了) * * @param outPdfFile 加了水印后要输出的路径 * @param InPdfFile 要加水印的原pdf文件路径 * @param markImagePath 水印图片路径 * @throws Exception */
  58. public static void addPdfMark( String outPdfFile,String InPdfFile, String markImagePath) throws Exception {
  59. PdfReader reader = new PdfReader(InPdfFile, "PDF".getBytes());
  60. PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(outPdfFile));
  61. PdfGState gs = new PdfGState();
  62. Image img = Image.getInstance(markImagePath);// 插入水印
  63. img.setRotationDegrees(30);//旋转 角度
  64. // img.scaleAbsolute(200,100);//自定义图片大小
  65. img.scalePercent(50);//图片依照比例缩放 百分之50
  66. gs.setFillOpacity(0.3f);//水印透明度
  67. int total = reader.getNumberOfPages(); //全部页
  68. PdfContentByte content;
  69. for (int i = 0; i < total; i++) {
  70. content = stamp.getUnderContent(+ 1); // 内容
  71. content.setGState(gs);
  72. float width = reader.getPageSize(i + 1).getWidth(); // 页宽度
  73. float height = reader.getPageSize(i + 1).getHeight(); // 页高度
  74. img.setAbsolutePosition(width / 2, height/3); //图片位置 第1张图
  75. content.addImage(img);
  76. img.setAbsolutePosition(width / 2, height/2); //图片位置 第2张图
  77. content.addImage(img);
  78. img.setAbsolutePosition(width / 2, height/4-50); //图片位置 第3张图
  79. content.addImage(img);
  80. }
  81. stamp.close();// 关闭
  82. reader.close();
  83. }
  84. }

使用教程

文字水印 (原PDF可以有背景颜色) 使用的最多

参数1 是加完水印后的PDF存储位置 参数2是原PDF 参数3是 添加的文字水印 参数4是位置 (1中间,2两边)

  1. @Test
  2. public void test2() throws Exception { //文字水印
  3. PdfWatermark.setWatermark(FILE_DIR + "createSamplePDF_sui.pdf", FILE_DIR + "createSamplePDF.pdf", "测试打印", 1);
  4. }

参数4:是1的情况

参数4:是2的情况

图片水印 (原PDF不能有背景颜色 否则图片水印无效)

参数1 是加完水印后的PDF存储位置 参数2是原PDF 参数3是水印图片位置

  1. @Test
  2. public void test2_1() throws Exception { //图片水印
  3. PdfWatermark.addPdfMark(FILE_DIR + "createSamplePDF_sui.pdf", FILE_DIR + "createSamplePDF.pdf", FILE_DIR + "baidu.jpg");
  4. }

删除PDF内的空页

  1. /** * * * @param pdfSourceFile 原文件 * @param pdfDestinationFile 处理后新生成的文件 */
  2. public static void removeBlankPdfPages(String pdfSourceFile, String pdfDestinationFile)
  3. {
  4. try
  5. {
  6. // step 1: create new reader
  7. PdfReader r = new PdfReader(pdfSourceFile);
  8. RandomAccessFileOrArray raf = new RandomAccessFileOrArray(pdfSourceFile);
  9. Document document = new Document(r.getPageSizeWithRotation(1));
  10. // step 2: create a writer that listens to the document
  11. PdfCopy writer = new PdfCopy(document, new FileOutputStream(pdfDestinationFile));
  12. // step 3: we open the document
  13. document.open();
  14. // step 4: we add content
  15. PdfImportedPage page = null;
  16. //loop through each page and if the bs is larger than 20 than we know it is not blank.
  17. //if it is less than 20 than we don't include that blank page.
  18. for (int i=1;i<=r.getNumberOfPages();i++)
  19. {
  20. //get the page content
  21. byte bContent [] = r.getPageContent(i,raf);
  22. ByteArrayOutputStream bs = new ByteArrayOutputStream();
  23. //write the content to an output stream
  24. bs.write(bContent);
  25. //add the page to the new pdf
  26. if (bs.size() > 20)
  27. {
  28. page = writer.getImportedPage(r, i);
  29. writer.addPage(page);
  30. }
  31. bs.close();
  32. }
  33. //close everything
  34. document.close();
  35. writer.close();
  36. raf.close();
  37. r.close();
  38. }
  39. catch(Exception e)
  40. {
  41. //do what you need here
  42. }
  43. }

压缩PDF到Zip

这种压缩是在生成PDF的时候直接写入到zip里

  1. //创建一个zip
  2. ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(FILE_DIR + "zipPDF.zip"));
  3. //创建PDF文件
  4. ZipEntry entry = new ZipEntry("hello_" + 1 + ".pdf");
  5. //将PDF添加到ZIP
  6. zip.putNextEntry(entry);
  7. Document document = new Document();
  8. PdfWriter writer = PdfWriter.getInstance(document, zip);
  9. // 后面内容
  10. writer.setCloseStream(false);
  11. document.open();
  12. document.add(new Paragraph("Hello " + 1));
  13. document.close();
  14. zip.closeEntry();
  15. zip.close();

合并PDF

读取所有文档然后追加到新的文档

  1. /** * * @param fileList 文档地址 * @param savepath 合并后地址 */
  2. public static void mergepdf(ArrayList<String> fileList, String savepath) {
  3. Document document = null;
  4. try {
  5. document = new Document(new PdfReader(fileList.get(0)).getPageSize(1));
  6. PdfCopy copy = new PdfCopy(document, new FileOutputStream(savepath));
  7. document.open();
  8. for (int i = 0; i < fileList.size(); i++) {
  9. PdfReader reader = new PdfReader(fileList.get(i));
  10. copy.addDocument(reader);
  11. reader.close();
  12. }
  13. } catch (IOException | DocumentException e) {
  14. e.printStackTrace();
  15. } finally {
  16. if (document != null) {
  17. document.close();
  18. }
  19. }
  20. }
  1. @Test
  2. public void he() throws IOException, DocumentException {
  3. ArrayList<String> arrayList=new ArrayList();
  4. arrayList.add(FILE_DIR + "splitPDF1.pdf");
  5. arrayList.add(FILE_DIR + "splitPDF2.pdf");
  6. mergepdf(arrayList, FILE_DIR + "mergePDF.pdf");
  7. }

读取PDF文档的页,然后一页一页追加到新的文档。 (也就是可以控制合并的页)

  1. /** * * @param fileList 文档地址 * @param savepath 合并后地址 */
  2. public static void mergepdf(ArrayList<String> fileList, String savepath) {
  3. Document document = null;
  4. try {
  5. document = new Document(new PdfReader(fileList.get(0)).getPageSize(1));
  6. PdfCopy copy = new PdfCopy(document, new FileOutputStream(savepath));
  7. document.open();
  8. for (int i = 0; i < fileList.size(); i++) {
  9. PdfReader reader = new PdfReader(fileList.get(i));
  10. copy.addDocument(reader);
  11. reader.close();
  12. }
  13. } catch (IOException e) {
  14. e.printStackTrace();
  15. } catch (DocumentException e) {
  16. e.printStackTrace();
  17. } finally {
  18. if (document != null) {
  19. document.close();
  20. }
  21. }
  22. }
  1. @Test
  2. public void he() throws IOException, DocumentException {
  3. ArrayList<String> arrayList=new ArrayList();
  4. arrayList.add(FILE_DIR + "splitPDF1.pdf");
  5. arrayList.add(FILE_DIR + "splitPDF2.pdf");
  6. mergepdf(arrayList, FILE_DIR + "mergePDF.pdf");
  7. }

添加批注和附件

  1. PdfWriter instance = PdfWriter.getInstance(doc, new FileOutputStream(FILE_DIR + "splitPDF2.pdf"));
  2. instance.setLinearPageMode();
  3. doc.open(); //打开PDF 默认为第一页
  4. doc.add(new Paragraph("1 page"));
  5. //给第一页添加批注
  6. doc.add(new Annotation("Title", "This is a annotation!"));
  7. doc.newPage();
  8. doc.add(new Paragraph("2 page"));
  9. //给第二页添加批注
  10. doc.add(new Annotation("Title", "This is a annotation!"));
  11. doc.newPage();
  12. doc.add(new Paragraph("3 page"));
  13. //给第三页添加附件
  14. Chunk chunk2 = new Chunk("\u00a0\u00a0"); // 必须有
  15. PdfAnnotation annotation = PdfAnnotation.createFileAttachment(
  16. instance, null, "Title", null,
  17. FILE_DIR+"baidu.jpg",
  18. "img.jpg");
  19. annotation.put(PdfName.NAME,
  20. new PdfString("Paperclip"));
  21. chunk2.setAnnotation(annotation);
  22. doc.add(chunk2);
  23. doc.close();

PDF表格

在PDF中整个表格没有控制位置的方法 但是会始终在PDF中间,而且还是自适应,并且独占一行,

插入表格

  1. doc.open(); //打开PDF 默认为第一页
  2. PdfPTable table = new PdfPTable(3);//设置3列
  3. PdfPCell cell;
  4. cell = new PdfPCell(new Phrase("Cell with colspan 3"));//设置列的内容
  5. cell.setColspan(3);//合并3列
  6. table.addCell(cell);//将内容添加到表格里第一行
  7. cell = new PdfPCell(new Phrase("Cell with rowspan 2")); //设置列的内容
  8. cell.setRowspan(2); //合并2行
  9. table.addCell(cell); //将内容添加到表格里第二行
  10. // 然后开始填空行
  11. table.addCell("row 1; cell 1");
  12. table.addCell("row 1; cell 2");
  13. table.addCell("row 2; cell 1");
  14. table.addCell("row 2; cell 2");
  15. doc.add(table);
  16. doc.close();

设置表格宽度位置

在上面代码的后面添加

  1. Rectangle rect = new Rectangle(PageSize.B4.rotate());
  2. Document doc = new Document(rect);
  3. PdfWriter instance = PdfWriter.getInstance(doc, new FileOutputStream(FILE_DIR + "splitPDF2.pdf"));
  4. doc.open(); //打开PDF 默认为第一页
  5. PdfPTable table = new PdfPTable(3);//设置3列
  6. PdfPCell cell;
  7. cell = new PdfPCell(new Phrase("Cell with colspan 3"));//设置列的内容
  8. cell.setColspan(3);//合并3列
  9. table.addCell(cell);//将内容添加到表格里第一行
  10. cell = new PdfPCell(new Phrase("Cell with rowspan 2")); //设置列的内容
  11. cell.setRowspan(2); //合并2行
  12. table.addCell(cell); //将内容添加到表格里第二行
  13. // 然后开始填空行
  14. table.addCell("row 1; cell 1");
  15. table.addCell("row 1; cell 2");
  16. table.addCell("row 2; cell 1");
  17. table.addCell("row 2; cell 2");
  18. doc.add(table);
  19. //宽度100%
  20. table.setWidthPercentage(100);
  21. doc.add(table);
  22. doc.add(new Paragraph("\n\n"));
  23. //宽度50% 居左
  24. table.setWidthPercentage(50);
  25. table.setHorizontalAlignment(Element.ALIGN_LEFT);
  26. doc.add(table);
  27. doc.add(new Paragraph("\n\n"));
  28. //宽度50% 居中
  29. table.setWidthPercentage(50);
  30. table.setHorizontalAlignment(Element.ALIGN_CENTER);
  31. doc.add(table);
  32. doc.add(new Paragraph("\n\n"));
  33. //宽度50% 居右
  34. table.setWidthPercentage(50);
  35. table.setHorizontalAlignment(Element.ALIGN_RIGHT);
  36. doc.add(table);
  37. doc.add(new Paragraph("\n\n"));
  38. //固定宽度 居中
  39. table.setTotalWidth(300);
  40. table.setLockedWidth(true);
  41. table.setHorizontalAlignment(Element.ALIGN_CENTER);
  42. doc.add(table);
  43. doc.close();

设置表格边框

  1. //没有边框
  2. PdfPTable table1 = new PdfPTable(3);
  3. table1.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
  4. table1.addCell(new Paragraph("Cell 1"));
  5. table1.addCell(new Paragraph("Cell 2"));
  6. table1.addCell(new Paragraph("Cell 3"));
  7. document.add(table1);

设置边框粗细颜色

  1. doc.open(); //打开PDF 默认为第一页
  2. //边框粗细颜色
  3. doc.newPage();
  4. Rectangle b1 = new Rectangle(0f, 0f);
  5. b1.setBorderWidthLeft(6f);//左边框大小
  6. b1.setBorderWidthBottom(5f);
  7. b1.setBorderWidthRight(4f);
  8. b1.setBorderWidthTop(2f);
  9. b1.setBorderColorLeft(BaseColor.RED);//左边框
  10. b1.setBorderColorBottom(BaseColor.ORANGE);//下边框
  11. b1.setBorderColorRight(BaseColor.YELLOW);
  12. b1.setBorderColorTop(BaseColor.GREEN);
  13. PdfPTable table2 = new PdfPTable(1);
  14. PdfPCell cell = new PdfPCell(new Paragraph("Cell 1"));
  15. cell.cloneNonPositionParameters(b1);
  16. table2.addCell(cell);
  17. doc.add(table2);
  18. doc.close();

设置表格的边框和背景颜色

  1. Rectangle rect = new Rectangle(PageSize.B4.rotate());
  2. Document doc = new Document(rect);
  3. PdfWriter instance = PdfWriter.getInstance(doc, new FileOutputStream(FILE_DIR + "splitPDF2.pdf"));
  4. doc.open(); //打开PDF 默认为第一页
  5. PdfPTable table = new PdfPTable(3);
  6. PdfPCell cell = new PdfPCell(new Paragraph("合并3列单元格",PdfFont.getChineseFont()));
  7. cell.setColspan(3);//合并3个列单元格
  8. table.addCell(cell);
  9. table.addCell("1.1");
  10. table.addCell("2.1");
  11. table.addCell("3.1");
  12. table.addCell("1.2");
  13. table.addCell("2.2");
  14. table.addCell("3.2");
  15. cell = new PdfPCell(new Paragraph("红色边框",PdfFont.getChineseFont()));
  16. //边框颜色
  17. cell.setBorderColor(new BaseColor(255, 0, 0));
  18. table.addCell(cell);
  19. cell = new PdfPCell(new Paragraph("合并2列元格,背景灰色",PdfFont.getChineseFont()));
  20. cell.setColspan(2);
  21. //背景色
  22. cell.setBackgroundColor(new BaseColor(0xC0, 0xC0, 0xC0));
  23. table.addCell(cell);
  24. table.setWidthPercentage(50); //设置表格的宽度
  25. doc.add(new Paragraph("表格1",PdfFont.getChineseFont()));
  26. doc.add(table);
  27. doc.close();

设置表格前后间隔

  1. Rectangle rect = new Rectangle(PageSize.B4.rotate());
  2. Document doc = new Document(rect);
  3. PdfWriter instance = PdfWriter.getInstance(doc, new FileOutputStream(FILE_DIR + "splitPDF2.pdf"));
  4. doc.open(); //打开PDF 默认为第一页
  5. PdfPTable table = new PdfPTable(3);
  6. PdfPCell cell = new PdfPCell(new Paragraph("合并3列单元格",PdfFont.getChineseFont()));
  7. cell.setColspan(3);//合并3个列单元格
  8. table.addCell(cell);
  9. table.addCell("1.1");
  10. table.addCell("2.1");
  11. table.addCell("3.1");
  12. table.addCell("1.2");
  13. table.addCell("2.2");
  14. table.addCell("3.2");
  15. doc.newPage();
  16. doc.add(new Paragraph("表格前的间距",PdfFont.getChineseFont()));
  17. table.setSpacingBefore(150f); //设置表格前的间距
  18. table.setSpacingAfter(150f); //设置表格后的间距
  19. doc.add(table);
  20. doc.add(new Paragraph("表格后的间距",PdfFont.getChineseFont()));
  21. doc.close();

设置单个的单元格宽度

  1. Rectangle rect = new Rectangle(PageSize.B4.rotate());
  2. Document doc = new Document(rect);
  3. PdfWriter instance = PdfWriter.getInstance(doc, new FileOutputStream(FILE_DIR + "splitPDF2.pdf"));
  4. doc.open(); //打开PDF 默认为第一页
  5. doc.add(new Paragraph("按百分比设置单元格宽度\n\n",PdfFont.getChineseFont()));
  6. float[] widths = {0.1f, 0.1f, 0.05f, 0.75f};
  7. PdfPTable table = new PdfPTable(widths);
  8. table.addCell("10%");
  9. table.addCell("10%");
  10. table.addCell("5%");
  11. table.addCell("75%");
  12. table.addCell("aa");
  13. table.addCell("aa");
  14. table.addCell("a");
  15. table.addCell("aaaaaaaaaaaaaaa");
  16. table.addCell("bb");
  17. table.addCell("bb");
  18. table.addCell("b");
  19. table.addCell("bbbbbbbbbbbbbbb");
  20. table.addCell("cc");
  21. table.addCell("cc");
  22. table.addCell("c");
  23. table.addCell("ccccccccccccccc");
  24. doc.add(table);
  25. doc.add(new Paragraph("\n\n"));
  26. doc.close();

设置单个的单元格高度

  1. Rectangle rect = new Rectangle(PageSize.B4.rotate());
  2. Document doc = new Document(rect);
  3. PdfWriter instance = PdfWriter.getInstance(doc, new FileOutputStream(FILE_DIR + "splitPDF2.pdf"));
  4. doc.open(); //打开PDF 默认为第一页
  5. PdfPTable table = new PdfPTable(2);
  6. PdfPCell cell;
  7. //设置高度
  8. table.addCell(new PdfPCell(new Paragraph("任意高度",PdfFont.getChineseFont())));
  9. cell = new PdfPCell(new Paragraph("1. blah blah\n2. blah blah blah\n3. blah blah\n4. blah blah blah\n5. blah blah\n6. blah blah blah\n7. blah blah\n8. blah blah blah"));
  10. table.addCell(cell);
  11. //固定高度
  12. table.addCell(new PdfPCell(new Paragraph("固定高度",PdfFont.getChineseFont())));
  13. cell.setFixedHeight(50f);
  14. table.addCell(cell);
  15. //最小高度
  16. table.addCell(new PdfPCell(new Paragraph("最小高度",PdfFont.getChineseFont())));
  17. cell = new PdfPCell(new Paragraph("最小高度:50",PdfFont.getChineseFont()));
  18. cell.setMinimumHeight(50f);
  19. table.addCell(cell);
  20. //最后一行拉长到page底部
  21. table.setExtendLastRow(true);
  22. table.addCell(new PdfPCell(new Paragraph("拉长最后一行",PdfFont.getChineseFont())));
  23. cell = new PdfPCell(new Paragraph("最后一行拉长到page底部",PdfFont.getChineseFont()));
  24. table.addCell(cell);
  25. doc.add(table);
  26. doc.close();

PDF之二维码和条形码

  1. Rectangle rect = new Rectangle(PageSize.B4.rotate());
  2. Document doc = new Document(rect);
  3. PdfWriter instance = PdfWriter.getInstance(doc, new FileOutputStream(FILE_DIR + "splitPDF2.pdf"));
  4. doc.open(); //打开PDF 默认为第一页
  5. //条形码
  6. PdfContentByte cd = instance.getDirectContent();
  7. Barcode128 code128 = new Barcode128();
  8. code128.setCode("http://www.baidu.com".trim());
  9. code128.setCodeType(Barcode128.CODE128);
  10. Image code128Image = code128.createImageWithBarcode(cd, null, null);
  11. code128Image.setAbsolutePosition(400,300);//条形码的位置
  12. code128Image.scalePercent(125);
  13. doc.add(code128Image);
  14. //二维码
  15. BarcodeQRCode qrcode = new BarcodeQRCode("http://www.baidu.com".trim(), 1, 1, null);
  16. Image qrcodeImage = qrcode.getImage();
  17. qrcodeImage.setAbsolutePosition(200,400);//二维码的位置
  18. qrcodeImage.scalePercent(200);
  19. doc.add(qrcodeImage);
  20. doc.close();

固定模板生成PDF方式

手动生成PDF发票(使用较少)

公司提供具体模板格式你使用itext画出来…:

我这里随便从网上找来了一个发票

链接:https://pan.baidu.com/s/11iy8M0_Oo0E1tzEITMSSLw
提取码:1234

下面就来演示将上面这张图完整的还原出来,其实很简单将这张图为背景就行了,自己在需要添加值得地方设置变量就可以了

  1. Rectangle rect = new Rectangle(PageSize.B4.rotate());
  2. Document doc = new Document(rect);
  3. PdfWriter instance = PdfWriter.getInstance(doc, new FileOutputStream(FILE_DIR + "splitPDF2.pdf"));
  4. doc.open(); //打开PDF 默认为第一页
  5. Image img = Image.getInstance(FILE_DIR+"37.jpg");
  6. img.scaleToFit(rect.getWidth(), rect.getHeight());
  7. doc.add(img);
  8. Phrase phrase1 = new Phrase("胡123",PdfFont.getChineseFont(12));
  9. Phrase phrase2 = new Phrase("212346512312311",PdfFont.getChineseFont(12));
  10. Phrase phrase3 = new Phrase("河南北京",PdfFont.getChineseFont(12));
  11. PdfContentByte canvas = instance.getDirectContent();
  12. // 参数1 默认就行 ,参数2默认就行,参数3内容,参数4x轴,参数5y轴,参数6字体旋转
  13. ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, phrase1, 230, 550, 0);
  14. ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, phrase2, 255, 530, 0);
  15. ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, phrase3, 240, 510, 0);
  16. doc.close();

这种方式的好处就是灵活,只需要提供画好的图片就行,

但是就是太麻烦了,需要自己控制文本的位置

常用于特别复杂的场景,使用word画不出来的场景,需要的样式花样特别多的场景,将样式效果脱落出去,我们只管文字的填充就行

利用word生成PDF(使用较多)

需要的工具

本地word(windows10自带 或者 wps 都行)
1.
在线word转PDF

免费word转PDF https://smallpdf.com/cn/word-to-pdf 一天2次(足够用了)

免费word转PDF http://www.pdfdo.com/doc-to-pdf.aspx 没有次数限制

免费word转PDF http://wordtopdf.55.la/ 限制每次转换大小最多100m 没有次数限制

… 网上一大堆都是免费的如果上面都过期了那么自己找
1.
给PDF添加表单控件的工具 Adobe Acrobat DC

链接:https://pan.baidu.com/s/1dah5Gxh-YZRGFbZiCEVXFg
提取码:1234
解压后记得断网,不然就不能使用,然后找到目录里的AcroPro.msi 双击安装就行 之后就可以正常使用了

第一步先创建好word模板

利用上面提供的网站进行转换为PDF,转换完成后双击打开PDF(使用Adobe Acrobat DC打开的)

如果你右下角没有的话在更多工具里是有的,然后进到下面这个页面

之后会自动在空白的地方补充,文本框 如果没有自动补充那么在最上面有工具栏里自行添加

然后我们需要调整 文框的大小和位置自行调整最合适的位置,否则字默认显示位置是top,我们需要将文本框变小刚好够一个字的大小

字体的大小默认是跟随着文本框的高度进行变换的…

我们还可以点击某个文本右键属性设置文本格式(字体颜色 字体大小 ,自动计算…太多了基本HTML表单能实现的功能这里都能实现)

如果你要设置多个的话可以 shift+鼠标左键或者ctrl+a全部选中进行统一设置都行

调整后的效果

第二步使用java代码给文本框中对应的属性赋值

需要使用到3个关键的对象

  1. PdfReader reader = new PdfReader(templateFile); // 模版文件目录
  2. PdfStamper ps = new PdfStamper(reader, new FileOutputStream(outFile)); // 生成的输出流
  3. AcroFields s = ps.getAcroFields(); //获取全部表单

案例:

  1. public void editPdfTemplate(String templateFile, String outFile) throws IOException, DocumentException {
  2. PdfReader reader = new PdfReader(templateFile); // 模版文件目录
  3. PdfStamper ps = new PdfStamper(reader, new FileOutputStream(outFile)); // 生成的输出流
  4. AcroFields s = ps.getAcroFields();
  5. //编辑文本域表单的内容
  6. s.setField("fill_1", "558");
  7. s.setField("fill_2", "99966");
  8. ps.setFormFlattening(true); // 模板中的变量赋值之后不能编辑
  9. ps.close();
  10. reader.close();
  11. }
  1. @Test
  2. public void mob() throws DocumentException, IOException {
  3. // 模板pdf 生成的pdf
  4. editPdfTemplate(FILE_DIR+"moban.pdf",FILE_DIR+"wordPDF.pdf");
  5. }

动态 freemarket模板生成PDF文档

我们使用 freemarket+itext+springboot 方式

一般pdf是用来生成发票或者简单的报告用的, 而某些领导蛋疼非要使用PDF导出数据统计报表你说气不气,没办法都是打工的不解决不行啊…

网上有很多种方式但是我一 一都进行了实验最后得出了结论就是 别乱搞没用,基本都失真,HTML转PDF基本都没有不失真的,

而且html的定位…很多css都不支持…浪费了我2天的我时间把网上各种生成PDF都试了个遍,最后还是放弃了,发现这种方式不能实现特别复杂的html页面 只能实现一些需要大量数据报表的显示,而且对样式要求不高,一般遇到这种情况都是采用导出Excel了而不是导出PDF了.

而且这种方式没法手动添加页只能自动适配页,也就是利用模板语法</#list xxx >,进行循环.

每页大具体大小是可以控制的多大都行但是必须要保证每次循环的内容必须都是在一页中. 之后每循环一次就是一页

我们HTML模板使用的是 Freemarker 也就是需要一些模板语法懂得都懂不会上百度…

简单来说就只需要3种语法就足够了:

获取值

  1. ${name}

if

  1. <#if var ??>
  2. 不是空
  3. <#else>
  4. 为空
  5. </#if>

循环

  1. <#list goodsList as goods>
  2. 姓名: ${goods.name} 年龄: ${goods.age} 性别${goods.sex} <br/>
  3. </#list>

我们还需要知道这种方式的弊端

css 各种定位 和 浮动 弹性布局 … 都不能使用 那么如何控制属性的位置呢?? 可以通过表格的方式 表格内地元素都能使用的.

比如 text-align 控制文本位置 valign 垂直对齐 align 水平对齐 , 行高 … 都可以进行控制 自己慢慢试试就行了
1.
图片不能加载本地图片 只能加载服务器图片, 也就是http请求的图片 如果想加载本地图片需要使用nginx做本地文件代理

  1. location /images/ {
  2. alias D:/nginx/nginx-1.19.10/html/images/; # 代理的路径
  3. autoindex on; #是否开启目录浏览
  4. }

当访问http://xxxx:80/images 就相当于在访问 D:/nginx/nginx-1.19.10/html/images/

使用的话我们只需要在后面在追加一个图片名称就行了 http://xxxx:80/images/1.jpg
1.
对于空值的校验,Freemarker 在渲染模板时不允许取值为空,如果某一项值可能为空,则必须添加校验,推荐取值方式

  1. <#if demoValue??>
  2. ${demoValue}
  3. </#if>

模板样式必须添加的

  1. /*-------------- 必须有的内容-------------------------*/
  2. /* 调整生成PDF页面宽和高 */
  3. @page {
  4. size: 340mm 350mm;
  5. }
  6. body{
  7. margin: 0;
  8. padding: 0;
  9. font-family: SimSun;
  10. }
  11. table {
  12. page-break-inside: auto;
  13. -fs-table-paginate: paginate;
  14. border-spacing: 0;
  15. cellspacing: 0;
  16. cellpadding: 0;
  17. border: solid 1px #ccc;
  18. padding: 2px 2px;
  19. }
  20. tr {
  21. page-break-inside: avoid;
  22. page-break-after: auto;
  23. }
  24. /*---------------必须有的内容------------------------*/

上代码就是防止生成的PDF时候表格内容超过当前页的时候不能自动适配

下面就详细演示所有代码 (web版下载)

项目结构

宋体字体

链接:https://pan.baidu.com/s/15uLOVmh2NZHG3g2zoPoaKw
提取码:1234

html模板

  1. <html>
  2. <head>
  3. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" >
  4. <title>Title</title>
  5. <style>
  6. /*-------------- 必须有的内容-------------------------*/
  7. /* 调整页面宽和高 */
  8. @page {
  9. size: 340mm 350mm;
  10. }
  11. body{
  12. margin: 0;
  13. padding: 0;
  14. font-family: SimSun;
  15. }
  16. table {
  17. page-break-inside: auto;
  18. -fs-table-paginate: paginate;
  19. border-spacing: 0;
  20. cellspacing: 0;
  21. cellpadding: 0;
  22. border: solid 1px #ccc;
  23. padding: 2px 2px;
  24. }
  25. tr {
  26. page-break-inside: avoid;
  27. page-break-after: auto;
  28. }
  29. /*---------------必须有的内容------------------------*/
  30. table{
  31. border: 1px solid #333;
  32. border-bottom: none;
  33. border-left: none;
  34. }
  35. td{
  36. height: 30px;
  37. border: 1px solid #333;
  38. border-top: none;
  39. text-align: center;
  40. }
  41. tr.title{
  42. font-weight: bold;
  43. }
  44. td.title{
  45. height: 50px;
  46. font-weight: bold;
  47. }
  48. td.value{
  49. color: blue;
  50. }
  51. td.content{
  52. font-size: 12px;
  53. text-align: left;
  54. }
  55. td.sign{
  56. text-align: left;
  57. height: 40px;
  58. }
  59. </style>
  60. </head>
  61. <body>
  62. <#list 1..max as i>
  63. <table class="table" cellspacing="0">
  64. <tr >
  65. <td class="title" colspan="10">
  66. 项目成员绩效考核表
  67. </td>
  68. </tr>
  69. <tr >
  70. <td style="width: 10%;" align="">
  71. 被考核者
  72. </td>
  73. <td class="value" style="width: 10%;">
  74. <#if employee??>
  75. <#if employee.name??>
  76. ${employee.name}
  77. </#if>
  78. </#if>
  79. </td>
  80. <td style="width: 10%;">
  81. 部门
  82. </td>
  83. <td colspan="2" class="value" style="width: 20%;">
  84. <#if employeeDepart??>
  85. <#if employeeDepart.name??>
  86. ${employeeDepart.name}
  87. </#if>
  88. </#if>
  89. </td>
  90. <td style="width: 10%;">
  91. 考核者
  92. </td>
  93. <td class="value" style="width: 10%;">
  94. <#if acceptUser??>
  95. <#if acceptUser.name??>
  96. ${acceptUser.name}
  97. </#if>
  98. </#if>
  99. </td>
  100. <td style="width: 10%;">
  101. 考核时间
  102. </td>
  103. <td colspan="2" class="value" style="width: 20%;">
  104. <#if statisticalTime??>
  105. ${statisticalTime}
  106. </#if>
  107. </td>
  108. </tr>
  109. <tr >
  110. <td colspan="10">
  111. 第一部分工作目标(权重80%)
  112. </td>
  113. </tr>
  114. <tr class="title">
  115. <td colspan="2">
  116. 指标名称
  117. </td>
  118. <td >
  119. 权重
  120. </td>
  121. <td colspan="3">
  122. 指标定义与评分标准
  123. </td>
  124. <td >
  125. 完成值
  126. </td>
  127. <td >
  128. 数据提供部门/人
  129. </td>
  130. <td >
  131. 自评得分
  132. </td>
  133. <td >
  134. 上级评分
  135. </td>
  136. </tr>
  137. <tr >
  138. <td colspan="2">
  139. 工作计划完成率
  140. </td>
  141. <td >
  142. 30%
  143. </td>
  144. <td colspan="3" class="content">
  145. 实际完成量/计划完成量*100%<br/>
  146. 1.完成比≥100%,本项为满分;<br/>
  147. 2.完成比在90%(含)-100%(不含),扣10分;<br/>
  148. 3.完成比在80%(含)-90%(不含),扣20分;<br/>
  149. 4.完成比在80%(不含)以下的,本项为0分
  150. </td>
  151. <td class="value">
  152. <#if jobCompletionRate??>
  153. ${jobCompletionRate*100}%
  154. </#if>
  155. </td>
  156. <td >
  157. 项目经理
  158. </td>
  159. <td class="value">
  160. <#if jobCompletionRateScore??>
  161. ${jobCompletionRateScore}
  162. </#if>
  163. </td>
  164. <td class="value">
  165. <#if jobCompletionRateSuperiorScore??>
  166. ${jobCompletionRateSuperiorScore}
  167. </#if>
  168. </td>
  169. </tr>
  170. <tr >
  171. <td colspan="2">
  172. 工作计划完成及时率
  173. </td>
  174. <td >
  175. 25%
  176. </td>
  177. <td colspan="3" class="content">
  178. 实际完成天数/计划完成天数*100%<br/>
  179. 1.完成比≦100%,本项为满分;<br/>
  180. 2.完成比在100%-110%(不含),扣5分;<br/>
  181. 3.完成比在110%(含)-130%(不含)扣10分;<br/>
  182. 4.完成比在130%(含)以上的,本项为0分
  183. </td>
  184. <td class="value">
  185. <#if finishRate??>
  186. ${finishRate*100}%
  187. </#if>
  188. </td>
  189. <td >
  190. 项目经理
  191. </td>
  192. <td class="value">
  193. <#if finishRateScore??>
  194. ${finishRateScore}
  195. </#if>
  196. </td>
  197. <td class="value">
  198. <#if finishRateSuperiorScore??>
  199. ${finishRateSuperiorScore}
  200. </#if>
  201. </td>
  202. </tr>
  203. <tr >
  204. <td colspan="2">
  205. 返工率
  206. </td>
  207. <td >
  208. 20%
  209. </td>
  210. <td colspan="3" class="content">
  211. 实际返工次数/计划返工次数*100%<br/>
  212. 1.完成比≤100%,本项为满分;<br/>
  213. 2.完成比在100%(不含)-110%(不含),扣10分;<br/>
  214. 3.完成比在110%(不含)-120%(含),扣15分;<br/>
  215. 4.完成比在120%(不含)以上的,本项为0分
  216. </td>
  217. <td class="value">
  218. <#if returnRate??>
  219. ${returnRate*100}%
  220. </#if>
  221. </td>
  222. <td >
  223. 项目经理<br/>
  224. 外型供应商
  225. </td>
  226. <td class="value">
  227. <#if returnRateScore??>
  228. ${returnRateScore}
  229. </#if>
  230. </td>
  231. <td class="value">
  232. <#if returnRateSuperiorScore??>
  233. ${returnRateSuperiorScore}
  234. </#if>
  235. </td>
  236. </tr>
  237. <tr >
  238. <td colspan="2">
  239. 技术文档资料保存完整性
  240. </td>
  241. <td >
  242. 15%
  243. </td>
  244. <td colspan="3" class="content">
  245. 实际上传资料数/要求上传资料数*100%<br/>
  246. 1.完成比100%,本项得满分;<br/>
  247. 2.完成比<100%,本项为0分
  248. </td>
  249. <td class="value">
  250. <#if uploadRate??>
  251. ${uploadRate*100}%
  252. </#if>
  253. </td>
  254. <td >
  255. 项目经理
  256. </td>
  257. <td class="value">
  258. <#if uploadRateScore??>
  259. ${uploadRateScore}
  260. </#if>
  261. </td>
  262. <td class="value">
  263. <#if uploadRateSuperiorScore??>
  264. ${uploadRateSuperiorScore}
  265. </#if>
  266. </td>
  267. </tr>
  268. <tr >
  269. <td colspan="2">
  270. 满意度
  271. </td>
  272. <td >
  273. 10%
  274. </td>
  275. <td colspan="3" class="content">
  276. 及时参加项目例会、积极汇报工作<br/>
  277. 总分10分<br/>
  278. 每遗漏一次,扣4分;扣完为止
  279. </td>
  280. <td >
  281. --
  282. </td>
  283. <td >
  284. 项目经理
  285. </td>
  286. <td class="value">
  287. <#if satisfactionScore??>
  288. ${satisfactionScore}
  289. </#if>
  290. </td>
  291. <td class="value">
  292. <#if satisfactionSuperiorScore??>
  293. ${satisfactionSuperiorScore}
  294. </#if>
  295. </td>
  296. </tr>
  297. <tr >
  298. <td colspan="10">
  299. 第二部分工作态度(权重20%)
  300. </td>
  301. </tr>
  302. <tr class="title">
  303. <td colspan="2">
  304. 工作态度指标
  305. </td>
  306. <td>
  307. 衡量方法
  308. </td>
  309. <td colspan="4">
  310. 衡量标准
  311. </td>
  312. <td >
  313. 权重
  314. </td>
  315. <td >
  316. 自评得分
  317. </td>
  318. <td >
  319. 上级评分
  320. </td>
  321. </tr>
  322. <tr >
  323. <td colspan="2">
  324. 责任心
  325. </td>
  326. <td>
  327. 上级评价
  328. </td>
  329. <td colspan="4" class="content">
  330. 1.仅仅能按上级要求完成本职工作(5分); <br/>
  331. 2.能够严格按照工作标准完成工作目标对本职工作负责到底,<br/>
  332. 工作中不推卸责任、不上交矛盾,失误较少(10分); <br/>
  333. 3.对待工作不怕繁琐、有耐心,考虑问题与做事细致、周到(15分); <br/>
  334. 4.对待工作精益求精,力求一次性做到完美(20分); <br/>
  335. 5.对团队成员拥有强烈的责任感,努力帮助团队成员提升工作质量(25分)
  336. </td>
  337. <td >
  338. 25%
  339. </td>
  340. <td class="value">
  341. <#if responsibilityScore??>
  342. ${responsibilityScore}
  343. </#if>
  344. </td>
  345. <td class="value">
  346. <#if responsibilitySuperiorScore??>
  347. ${responsibilitySuperiorScore}
  348. </#if>
  349. </td>
  350. </tr>
  351. <tr >
  352. <td colspan="2">
  353. 主动性
  354. </td>
  355. <td>
  356. 上级评价
  357. </td>
  358. <td colspan="4" class="content">
  359. 1.按上级安排/ 指示做事,安排什么做什么(5分)<br/>
  360. 2.按自己的职位职责做事,工作任务大多能完成;<br/>
  361. 同时对工作中出现的问题,也能被动反应,予以处理(10分)<br/>
  362. 3.对自己的工作大致有思考,上级安排的任务能有效配合确定工作计划,<br/>
  363. 并按计划完成工作任务;同时能积极处理工作中出现的各种问题,<br/>
  364. 需要请示或上级支持时也能按程序办理(15分)<br/>
  365. 4.提前思考、主动安排自己的工作计划,并将之主动与上级沟通、协商、确定,<br/>
  366. 按计划推进、完成工作任务;对工作问题提前预防,并妥善处理各类问题;<br/>
  367. 能积极主动地协助同事完成职责范围外的其他工作(20分)<br/>
  368. 5.上级只给出一个方向或任务,既能独立地制定计划、组织资源、推进实施、保证完成,<br/>
  369. 支持、鼓励团队成员与周围同事积极主动开展工作,<br/>
  370. 能营造积极、主动的文化氛围(25)
  371. </td>
  372. <td >
  373. 25%
  374. </td>
  375. <td class="value">
  376. <#if initiativeScore??>
  377. ${initiativeScore}
  378. </#if>
  379. </td>
  380. <td class="value">
  381. <#if initiativeSuperiorScore??>
  382. ${initiativeSuperiorScore}
  383. </#if>
  384. </td>
  385. </tr>
  386. <tr >
  387. <td colspan="2">
  388. 团队合作
  389. </td>
  390. <td>
  391. 上级评价
  392. </td>
  393. <td colspan="4" class="content">
  394. 1.积极融入团队并乐于接受同事帮助,配合团队完成工作(5分)<br/>
  395. 2.主动给予同事必要的帮助;碰到困难时,善于利用团队的力量解决问题(10分)<br/>
  396. 3.决策前积极发表个人意见,充分参与团队讨论;决策后,个人无论是否有异议,<br/>
  397. 必须从行动上完全予以支持(15分);<br/>
  398. 4.能够客观认识同事的优缺点,并在工作中充分体现“对事不对人”的原则(20分)<br/>
  399. 5.能够以积极正面的心态去影响团队,并改善团队表现和氛围(25分)<br/>
  400. </td>
  401. <td >
  402. 25%
  403. </td>
  404. <td class="value">
  405. <#if teamCooperationScore??>
  406. ${teamCooperationScore}
  407. </#if>
  408. </td>
  409. <td class="value">
  410. <#if teamCooperationSuperiorScore??>
  411. ${teamCooperationSuperiorScore}
  412. </#if>
  413. </td>
  414. </tr>
  415. <tr >
  416. <td colspan="2">
  417. 保密意识
  418. </td>
  419. <td>
  420. 上级评价
  421. </td>
  422. <td colspan="4" class="content">
  423. 1.对岗位的保密责任有一定的认识(5分);<br/>
  424. 2.熟悉公司保密协议,明确职责范围内的保密事项,并采取相应的维护措施(10分)<br/>
  425. 3.以身作则,自觉、严格遵守保密协议,对保密协议未明确界定的问题能够很好的处理(15分)<br/>
  426. 4.影响身边的同事,宣传保密意识,随时提醒同事;发现保密协议的缺陷和漏洞<br/>
  427. 能及时向有关部门报告,并提出完善建议(20分);<br/>
  428. 5.获悉他人违反和破坏保密协议时,积极抵制,能够及时向公司有关部门报告,<br/>
  429. 并分情况采取积极措施以最大限度减少恶性后果,处理得当(25分)
  430. </td>
  431. <td >
  432. 25%
  433. </td>
  434. <td class="value">
  435. <#if secrecyScore??>
  436. ${secrecyScore}
  437. </#if>
  438. </td>
  439. <td class="value">
  440. <#if secrecySuperiorScore??>
  441. ${secrecySuperiorScore}
  442. </#if>
  443. </td>
  444. </tr>
  445. <tr >
  446. <td colspan="8">
  447. 合计
  448. </td>
  449. <td class="value">
  450. <#if totalScore??>
  451. ${totalScore}
  452. </#if>
  453. </td>
  454. <td class="value">
  455. <#if totalSuperiorScore??>
  456. ${totalSuperiorScore}
  457. </#if>
  458. </td>
  459. </tr>
  460. <tr >
  461. <td colspan="2">
  462. 等级评定规则
  463. </td>
  464. <td class="content" colspan="5">
  465. A:优秀(100分以上)<br/>
  466. B:良好(90-100分)<br/>
  467. C:合格(80-90分)<br/>
  468. D:基本合格(70-80分)<br/>
  469. E:需改进(60-70分)<br/>
  470. F:不合格(60分以下)
  471. </td>
  472. <td >
  473. 等级评定
  474. </td>
  475. <td class="value" colspan="2">
  476. <#if grade??>
  477. ${grade}
  478. </#if>
  479. </td>
  480. </tr>
  481. <tr style="height: 100px;" >
  482. <td colspan="2">
  483. 自我总结
  484. </td>
  485. <td colspan="8" class="content value">
  486. <#if selfSummary??>
  487. ${selfSummary}
  488. </#if>
  489. </td>
  490. </tr>
  491. <tr >
  492. <td rowspan="2" colspan="2">
  493. 考核结果确认
  494. </td>
  495. <td class="sign" colspan="4">
  496. 考核者签名:
  497. </td>
  498. <td class="sign" colspan="4">
  499. 日期:
  500. </td>
  501. </tr>
  502. <tr>
  503. <td class="sign" colspan="4">
  504. 被考核者签名:
  505. </td>
  506. <td class="sign" colspan="4">
  507. 日期:
  508. </td>
  509. </tr>
  510. </table>
  511. </#list>
  512. </body>
  513. </html>

获取资源路径工具类

  1. package com.pdf.utils;
  2. import org.springframework.util.ResourceUtils;
  3. import java.io.File;
  4. import java.io.FileNotFoundException;
  5. /** * @Description: 项目静态资源文件工具类 * 仅可用于包含在web项目中的资源文件路径,资源文件必须放置于 web 模块下 */
  6. public class ResourceFileUtil {
  7. /** * 获取资源文件 * * @param relativePath 资源文件相对路径(相对于 resources路径,路径 + 文件名) * eg: "templates/pdf_export_demo.ftl" * @return * @throws FileNotFoundException */
  8. public static File getFile(String relativePath) throws FileNotFoundException {
  9. if (relativePath == null || relativePath.length() == 0) {
  10. return null;
  11. }
  12. if (relativePath.startsWith("/")) {
  13. relativePath = relativePath.substring(1);
  14. }
  15. File file = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX
  16. + relativePath);
  17. return file;
  18. }
  19. /** * 获取资源绝对路径 * * @param relativePath 资源文件相对路径(相对于 resources路径,路径 + 文件名) * eg: "templates/pdf_export_demo.ftl" * @return * @throws FileNotFoundException */
  20. public static String getAbsolutePath(String relativePath) throws FileNotFoundException {
  21. return getFile(relativePath).getAbsolutePath();
  22. }
  23. /** * 获取资源父级目录 * * @param relativePath 资源文件相对路径(相对于 resources路径,路径 + 文件名) * eg: "templates/pdf_export_demo.ftl" * @return * @throws FileNotFoundException */
  24. public static String getParent(String relativePath) throws FileNotFoundException {
  25. return getFile(relativePath).getParent();
  26. }
  27. /** * 获取资源文件名 * * @param relativePath 资源文件相对路径(相对于 resources路径,路径 + 文件名) * eg: "templates/pdf_export_demo.ftl" * @return * @throws FileNotFoundException */
  28. public static String getFileName(String relativePath) throws FileNotFoundException {
  29. return getFile(relativePath).getName();
  30. }
  31. }

生成PDF工具类

  1. package com.pdf.utils;
  2. import com.lowagie.text.DocumentException;
  3. import com.lowagie.text.pdf.BaseFont;
  4. import freemarker.template.Configuration;
  5. import freemarker.template.Template;
  6. import freemarker.template.TemplateException;
  7. import freemarker.template.TemplateExceptionHandler;
  8. import org.apache.commons.lang3.StringUtils;
  9. import org.jsoup.Jsoup;
  10. import org.jsoup.nodes.Document;
  11. import org.jsoup.nodes.Element;
  12. import org.jsoup.nodes.Entities;
  13. import org.jsoup.select.Elements;
  14. import org.springframework.http.HttpHeaders;
  15. import org.springframework.http.HttpStatus;
  16. import org.springframework.http.MediaType;
  17. import org.springframework.http.ResponseEntity;
  18. import org.xhtmlrenderer.pdf.ITextFontResolver;
  19. import org.xhtmlrenderer.pdf.ITextRenderer;
  20. import java.io.*;
  21. import java.util.Map;
  22. public class PDFUtil {
  23. // 必须在resoures下面
  24. private static String font="templates/font/simsun.ttf"; //字体
  25. private static String templ="templates/pdf_export_employee_kpi.html"; //模板
  26. private PDFUtil(){}
  27. private volatile static Configuration configuration;
  28. static {
  29. if (configuration == null) {
  30. synchronized (PDFUtil.class) {
  31. if (configuration == null) {
  32. configuration = new Configuration(Configuration.VERSION_2_3_28);
  33. }
  34. }
  35. }
  36. }
  37. /** * freemarker 引擎渲染 html * * @param dataMap 传入 html 模板的 Map 数据 * @param ftlFilePath html 模板文件相对路径(相对于 resources路径,路径 + 文件名) * eg: "templates/pdf_export_demo.ftl" * @return */
  38. public static String freemarkerRender(Map<String, Object> dataMap, String ftlFilePath) {
  39. Writer out = new StringWriter();
  40. configuration.setDefaultEncoding("UTF-8");
  41. configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
  42. try {
  43. configuration.setDirectoryForTemplateLoading(new File(ResourceFileUtil.getParent(ftlFilePath)));
  44. configuration.setLogTemplateExceptions(false);
  45. configuration.setWrapUncheckedExceptions(true);
  46. Template template = configuration.getTemplate(ResourceFileUtil.getFileName(ftlFilePath));
  47. template.process(dataMap, out);
  48. out.flush();
  49. return out.toString();
  50. } catch (IOException e) {
  51. e.printStackTrace();
  52. } catch (TemplateException e) {
  53. e.printStackTrace();
  54. } finally {
  55. try {
  56. out.close();
  57. } catch (IOException e) {
  58. e.printStackTrace();
  59. }
  60. }
  61. return null;
  62. }
  63. /** * 使用 iText 生成 PDF 文档 * * @param htmlTmpStr html 模板文件字符串 * @param fontFile 所需字体文件(相对路径+文件名) * */
  64. public static byte[] createPDF(String htmlTmpStr, String fontFile) {
  65. ByteArrayOutputStream outputStream = null;
  66. byte[] result = null;
  67. try {
  68. outputStream = new ByteArrayOutputStream();
  69. ITextRenderer renderer = new ITextRenderer();
  70. renderer.setDocumentFromString(htmlTmpStr);
  71. ITextFontResolver fontResolver = renderer.getFontResolver();
  72. // 解决中文支持问题,需要所需字体(ttc)文件
  73. fontResolver.addFont(ResourceFileUtil.getAbsolutePath(fontFile),BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
  74. renderer.layout();
  75. renderer.createPDF(outputStream);
  76. result=outputStream.toByteArray();
  77. if(outputStream != null) {
  78. outputStream.flush();
  79. outputStream.close();
  80. }
  81. } catch (FileNotFoundException e) {
  82. e.printStackTrace();
  83. } catch (DocumentException e) {
  84. e.printStackTrace();
  85. } catch (IOException e) {
  86. e.printStackTrace();
  87. }
  88. return result;
  89. }
  90. /** * PDF 文件导出 * * @return */
  91. public static ResponseEntity<?> export(Map<String, Object> dataMap, String pdfName) {
  92. HttpHeaders headers = new HttpHeaders();
  93. /** * 数据导出(PDF 格式) */
  94. String htmlStr = PDFUtil.freemarkerRender(dataMap, templ);
  95. String s = formatHtml(htmlStr);
  96. System.out.println(s);
  97. byte[] pdfBytes = PDFUtil.createPDF(s, font);
  98. if (pdfBytes != null && pdfBytes.length > 0) {
  99. String fileName=null;
  100. if (pdfName!=null){
  101. fileName= pdfName;
  102. }else {
  103. fileName = System.currentTimeMillis() + (int) (Math.random() * 90000 + 10000) + ".pdf";
  104. }
  105. headers.setContentDispositionFormData("attachment", fileName);
  106. headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
  107. return new ResponseEntity<byte[]>(pdfBytes, headers, HttpStatus.OK);
  108. }
  109. headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
  110. return new ResponseEntity<String>("{ \"code\" : \"404\", \"message\" : \"not found\" }",
  111. headers, HttpStatus.NOT_FOUND);
  112. }
  113. public static ResponseEntity<?> export(Map<String, Object> dataMap) {
  114. return export( dataMap ,null);
  115. }
  116. /** * 使用jsoup规范化html * * @param html html内容 * @return 规范化后的html */
  117. private static String formatHtml(String html) {
  118. Document doc = Jsoup.parse(html);
  119. // 去除过大的宽度
  120. String style = doc.attr("style");
  121. if (StringUtils.isNotEmpty(style) && style.contains("width")) {
  122. doc.attr("style", "");
  123. }
  124. Elements divs = doc.select("div");
  125. for (Element div : divs) {
  126. String divStyle = div.attr("style");
  127. if (StringUtils.isNotEmpty(divStyle) && divStyle.contains("width")) {
  128. div.attr("style", "");
  129. }
  130. }
  131. // jsoup生成闭合标签
  132. doc.outputSettings().syntax(org.jsoup.nodes.Document.OutputSettings.Syntax.xml);
  133. doc.outputSettings().escapeMode(Entities.EscapeMode.xhtml);
  134. return doc.html();
  135. }
  136. }

Controller

  1. package com.pdf.controller;
  2. import com.pdf.utils.PDFUtil;
  3. import org.springframework.http.HttpHeaders;
  4. import org.springframework.http.HttpStatus;
  5. import org.springframework.http.MediaType;
  6. import org.springframework.http.ResponseEntity;
  7. import org.springframework.web.bind.annotation.GetMapping;
  8. import org.springframework.web.bind.annotation.RestController;
  9. import java.util.Date;
  10. import java.util.HashMap;
  11. import java.util.Map;
  12. @RestController
  13. public class PdfController {
  14. /** * PDF 文件导出 */
  15. @GetMapping(value = "/pdf")
  16. public ResponseEntity<?> export(){
  17. try {
  18. Map<String, Object> dataMap = new HashMap<>(16);
  19. dataMap.put("statisticalTime",new Date().toString());
  20. dataMap.put("max",5);
  21. ResponseEntity<?> responseEntity = PDFUtil.export(dataMap);
  22. return responseEntity;
  23. } catch (Exception e) {
  24. e.printStackTrace();
  25. }
  26. HttpHeaders headers = new HttpHeaders();
  27. headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
  28. return new ResponseEntity<String>("{ \"code\" : \"404\", \"message\" : \"not found\" }",
  29. headers, HttpStatus.NOT_FOUND);
  30. }
  31. }

启动类

  1. package com.pdf;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. @SpringBootApplication(scanBasePackages = "com")
  5. public class ApplictioBoot {
  6. public static void main(String[] args) {
  7. SpringApplication.run(ApplictioBoot.class,args);
  8. }
  9. }

然后进行测试 访问 http://localhost:8080/pdf

注意:如果上面 word 模板方式或者 html+freemaret模板方式都不满足你的业务需求的话那么,你就需要手写Itext的方式进行生成PDF了

web页面下载方式

有两种方式

  1. 先生成PDF文件到本地 然后在读取本地pdf文件将二进制数据发送到前端之后在删除本地生成的PDF
  2. 直接在缓存中生成pdf 生成后直接想二进制发给前端

我们常用于第二种方式 ,而第一种方式只需要会io流就行了这里就不多讲了,直接上第二种方式的代码就行了

  1. package com.pdf.utils;
  2. import com.itextpdf.text.*;
  3. import com.itextpdf.text.pdf.PdfPCell;
  4. import com.itextpdf.text.pdf.PdfPTable;
  5. import com.itextpdf.text.pdf.PdfWriter;
  6. import javax.servlet.http.HttpServletResponse;
  7. import java.io.*;
  8. import java.net.URLEncoder;
  9. public class PdfDownLoadUtils {
  10. public static ByteArrayOutputStream ini() throws DocumentException {
  11. Rectangle rect = new Rectangle(PageSize.B4.rotate());
  12. Document doc = new Document(rect);
  13. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  14. PdfWriter instance = PdfWriter.getInstance(doc, baos);
  15. doc(doc);
  16. return baos;
  17. }
  18. private static void doc(Document doc) throws DocumentException {
  19. doc.open(); //打开PDF 默认为第一页
  20. PdfPTable table = new PdfPTable(3);//设置3列
  21. PdfPCell cell;
  22. cell = new PdfPCell(new Phrase("Cell with colspan 3"));//设置列的内容
  23. cell.setColspan(3);//合并3列
  24. table.addCell(cell);//将内容添加到表格里第一行
  25. cell = new PdfPCell(new Phrase("Cell with rowspan 2")); //设置列的内容
  26. cell.setRowspan(2); //合并2行
  27. table.addCell(cell); //将内容添加到表格里第二行
  28. // 然后开始填空行
  29. table.addCell("row 1; cell 1");
  30. table.addCell("row 1; cell 2");
  31. table.addCell("row 2; cell 1");
  32. table.addCell("row 2; cell 2");
  33. doc.add(table);
  34. doc.close();
  35. }
  36. }

核心代码

  1. /** * PDF 文件导出 */
  2. @GetMapping(value = "/pdfDow")
  3. public ResponseEntity<?> export1(HttpServletRequest request, HttpServletResponse response) {
  4. HttpHeaders headers = new HttpHeaders();
  5. String pdName="student.pdf"; //文件名称
  6. //设置页面编码格式
  7. try {
  8. ByteArrayOutputStream ini = PdfDownLoadUtils.ini();
  9. // 页面打开PDF 不下载
  10. // response.setContentLength(ini.size());
  11. // OutputStream out = response.getOutputStream();
  12. // ini.writeTo(out);
  13. // return new ResponseEntity<byte[]>( headers, HttpStatus.OK);
  14. // 下载PDF
  15. headers.setContentDispositionFormData("attachment", pdName);
  16. headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
  17. return new ResponseEntity<byte[]>(ini.toByteArray(), headers, HttpStatus.OK);
  18. } catch (DocumentException e) {
  19. e.printStackTrace();
  20. }
  21. // 返回错误信息
  22. headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
  23. return new ResponseEntity<String>("{ \"code\" : \"404\", \"message\" : \"not found\" }",
  24. headers, HttpStatus.NOT_FOUND);
  25. }

如果非要使用第一种方式的话只需要下面这一个方法就行了

  1. public static void downloadFile(String path, HttpServletResponse response) {
  2. try {
  3. // path是指欲下载的文件的路径。
  4. File file = new File(path);
  5. // 取得文件名。
  6. String filename = file.getName();
  7. // 以流的形式下载文件。
  8. InputStream fis = new BufferedInputStream(new FileInputStream(path));
  9. byte[] buffer = new byte[fis.available()];
  10. fis.read(buffer);
  11. fis.close();
  12. // 清空response
  13. response.reset();
  14. // 设置response的Header
  15. response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "utf-8"));
  16. response.addHeader("Content-Length", "" + file.length());
  17. OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
  18. response.setContentType("application/octet-stream");
  19. toClient.write(buffer);
  20. toClient.flush();
  21. toClient.close();
  22. } catch (IOException ex) {
  23. ex.printStackTrace();
  24. }
  25. }
  1. /** * PDF 文件导出 */
  2. @GetMapping(value = "/pdfDow")
  3. public ResponseEntity<?> export1(HttpServletRequest request, HttpServletResponse response){
  4. try {
  5. int a=1/0;
  6. PdfDownLoadUtils.downloadFile(ResourceFileUtil.getAbsolutePath("PDF/student.pdf"),response);
  7. } catch (Exception e) {
  8. e.printStackTrace();
  9. }
  10. HttpHeaders headers = new HttpHeaders();
  11. // 失败返回错误信息
  12. headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
  13. return new ResponseEntity<String>("{ \"code\" : \"404\", \"message\" : \"not found\" }",
  14. headers, HttpStatus.NOT_FOUND);
  15. }
  16. table.addCell("row 2; cell 1");
  17. table.addCell("row 2; cell 2");
  18. doc.add(table);
  19. doc.close();
  20. }
  21. }

核心代码

  1. /** * PDF 文件导出 */
  2. @GetMapping(value = "/pdfDow")
  3. public ResponseEntity<?> export1(HttpServletRequest request, HttpServletResponse response) {
  4. HttpHeaders headers = new HttpHeaders();
  5. String pdName="student.pdf"; //文件名称
  6. //设置页面编码格式
  7. try {
  8. ByteArrayOutputStream ini = PdfDownLoadUtils.ini();
  9. // 页面打开PDF 不下载
  10. // response.setContentLength(ini.size());
  11. // OutputStream out = response.getOutputStream();
  12. // ini.writeTo(out);
  13. // return new ResponseEntity<byte[]>( headers, HttpStatus.OK);
  14. // 下载PDF
  15. headers.setContentDispositionFormData("attachment", pdName);
  16. headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
  17. return new ResponseEntity<byte[]>(ini.toByteArray(), headers, HttpStatus.OK);
  18. } catch (DocumentException e) {
  19. e.printStackTrace();
  20. }
  21. // 返回错误信息
  22. headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
  23. return new ResponseEntity<String>("{ \"code\" : \"404\", \"message\" : \"not found\" }",
  24. headers, HttpStatus.NOT_FOUND);
  25. }

如果非要使用第一种方式的话只需要下面这一个方法就行了

  1. public static void downloadFile(String path, HttpServletResponse response) {
  2. try {
  3. // path是指欲下载的文件的路径。
  4. File file = new File(path);
  5. // 取得文件名。
  6. String filename = file.getName();
  7. // 以流的形式下载文件。
  8. InputStream fis = new BufferedInputStream(new FileInputStream(path));
  9. byte[] buffer = new byte[fis.available()];
  10. fis.read(buffer);
  11. fis.close();
  12. // 清空response
  13. response.reset();
  14. // 设置response的Header
  15. response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "utf-8"));
  16. response.addHeader("Content-Length", "" + file.length());
  17. OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
  18. response.setContentType("application/octet-stream");
  19. toClient.write(buffer);
  20. toClient.flush();
  21. toClient.close();
  22. } catch (IOException ex) {
  23. ex.printStackTrace();
  24. }
  25. }
  1. /** * PDF 文件导出 */
  2. @GetMapping(value = "/pdfDow")
  3. public ResponseEntity<?> export1(HttpServletRequest request, HttpServletResponse response){
  4. try {
  5. int a=1/0;
  6. PdfDownLoadUtils.downloadFile(ResourceFileUtil.getAbsolutePath("PDF/student.pdf"),response);
  7. } catch (Exception e) {
  8. e.printStackTrace();
  9. }
  10. HttpHeaders headers = new HttpHeaders();
  11. // 失败返回错误信息
  12. headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
  13. return new ResponseEntity<String>("{ \"code\" : \"404\", \"message\" : \"not found\" }",
  14. headers, HttpStatus.NOT_FOUND);
  15. }

相关文章