SpringBoot集成文件 - 如何集成itextpdf导出PDF?itext的变化? 学问准备
需求理解itext,以及itext历史版本变化,以及license的问题。
什么是itext
来源于百度百科:iText是著名的开放源码的站点sourceforge一个项目(由Bruno Lowagie编写),是一个用Java和.NET言语写的库,用来创立和修正PDF文件。经过iText不只能够生成PDF或rtf的文档,而且能够将XML、Html文件转化为PDF文件。 iText的装置十分便当,下载iText.jar文件后,只需求在系统的CLASSPATH中参加iText.jar的途径,在程序中就能够运用iText类库了。
iText提供除了根本的创立、修正PDF文件外的其他高级的PDF特性,例如基于PKI的签名,40位和128位加密,颜色校正,带标签的PDF,PDF表单(AcroForms),PDF/X,经过ICC配置文件和条形码停止颜色管理。这些特性被一些产品和效劳中运用,包括Eclipse BIRT,Jasper Reports,JBoss Seam,Windward Reports和pdftk。 普通状况下,iText运用在有以下一个请求的项目中:
内容无法提早应用:取决于用户的输入或实时的数据库信息。 由于内容,页面过多,PDF文档不能手动生成。 文档需在无人参与,批处置形式下自动创立。 内容被定制或个性化;例如,终端客户的名字需求标志在大量的页面上。
itext的历史版本和License问题
运用itext一定要理解其版本历史,和License问题,在早前版本运用的是MPL和LGPL双答应协议,在5.x以上版本中运用的是AGPLv3(这个协议意味着,只要个人用处和开源的项目才干运用itext这个库,否则是需求收费的)
iText 0.x-2.x/iTextSharp 3.x-4.x
更新时间是2000-2009 运用的是MPL和LGPL双答应协议 最近的更新是2009年,版本号是iText 2.1.7/iTextSharp 4.1.6.0 此时引入包的GAV版本如下:
com.lowagie itext 2.1.7
iText 5.x和iTextSharp 5.x
更新时间是2009-2016, 公司化运作,并规范化和进步性能 开端运用AGPLv3协议
只要个人用处和开源的项目才干运用itext这个库,否则是需求收费的
iTextSharp被设计成iText库的.NET版本,并且与iText版本号同步,iText 5.0.0和iTextSharp5.0.0同时发布 新功用不在这里面增加,但是官方会修复重要的bug 此时引入包的GAV版本如下:
com.itextpdf itextpdf 5.5.13.3
iText 7.x
更新时间是2016到如今 AGPLv3协议 完整重写,重点关注可扩展性和模块化 不适用iTextSharp这个称号,都统称为iText,有Java和.Net版本 JDK 1.7+ 此时引入包的GAV版本如下:
com.itextpdf itext7-core 7.2.2 pom
// 2. 绑定输出流(经过pdfwriter)
PdfWriter.getInstance(document, os);
// 3. 翻开文档
document.open();
// 4. 往文档中添加内容
document.add(xxx);
// 5. 关闭文档
document.close();
return document;
} 复制代码 document中添加的Element有哪些呢?
需求阐明下如下概念之前的差异:
Chunk:文档的文本的最小块单位 Phrase:一系列以特定间距(两行之间的间隔)作为参数的块 Paragraph:段落是一系列块和(或)短句。同短句一样,段落有肯定的间距。用户还能够指定缩排;在边和(或)右边保存一定空白,段落能够左对齐、右对齐和居中对齐。添加到文档中的每一个段落将自动另起一行。
(其它从字面上就能够看出,所以这里详细就不做解释了) 完成案例
这里展现SpringBoot集成itext5导出PDF的例子。
Pom依赖 引入poi的依赖包 com.itextpdf itextpdf 5.5.13.3 com.itextpdf itext-asian 5.2.0
import java.io.OutputStream;
import javax.servlet.http.HttpServletResponse;
import io.swagger.annotations.ApiOperation; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import tech.pdai.springboot.file.word.poi.service.IUserService;
/**
- @author pdai
*/
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired private IUserService userService;
@ApiOperation("Download Word") @GetMapping("/word/download") public void download(HttpServletResponse response) { try { XWPFDocument document = userService.generateWordXWPFDocument(); response.reset(); response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-disposition", "attachment;filename=user_world_" + System.currentTimeMillis() + ".docx"); OutputStream os = response.getOutputStream(); document.write(os); os.close(); } catch (Exception e) { e.printStackTrace(); } }
}
复制代码 UserServiceImple中导出PDF办法 @Override public Document generateItextPdfDocument(OutputStream os) throws Exception { // document Document document = new Document(PageSize.A4); PdfWriter.getInstance(document, os);
// open
document.open();
// add content - pdf meta information
document.addAuthor("pdai");
document.addCreationDate();
document.addTitle("pdai-pdf-itextpdf");
document.addKeywords("pdf-pdai-keyword");
document.addCreator("pdai");
// add content - page content
// Title
document.add(createTitle("Java 全栈学问体系"));
// Chapter 1
document.add(createChapterH1("1. 学问准备"));
document.add(createChapterH2("1.1 什么是POI"));
document.add(createParagraph("Apache POI 是创立和维护操作各种契合Office Open XML(OOXML)规范和微软的OLE 2复合文档格式(OLE2)的Java API。用它能够运用Java读取和创立,修正MS Excel文件.而且,还能够运用Java读取和创立MS Word和MSPowerPoint文件。更多请参考[官方文档](https://poi.apache.org/index.html)"));
document.add(createChapterH2("1.2 POI中根底概念"));
document.add(createParagraph("生成xls和xlsx有什么区别?POI对Excel中的对象的封装对应关系?"));
// Chapter 2
document.add(createChapterH1("2. 完成案例"));
document.add(createChapterH2("2.1 用户列表示例"));
document.add(createParagraph("以导出用户列表为例"));
// 表格
List<User> userList = getUserList();
PdfPTable table = new PdfPTable(new float[]{20, 40, 50, 40, 40});
table.setTotalWidth(500);
table.setLockedWidth(true);
table.setHorizontalAlignment(Element.ALIGN_CENTER);
table.getDefaultCell().setBorder(1);
for (int i = 0; i < userList.size(); i++) {
table.addCell(createCell(userList.get(i).getId() + ""));
table.addCell(createCell(userList.get(i).getUserName()));
table.addCell(createCell(userList.get(i).getEmail()));
table.addCell(createCell(userList.get(i).getPhoneNumber() + ""));
table.addCell(createCell(userList.get(i).getDescription()));
}
document.add(table);
document.add(createChapterH2("2.2 图片导出示例"));
document.add(createParagraph("以导出图片为例"));
// 图片
Resource resource = new ClassPathResource("pdai-guli.png");
Image image = Image.getInstance(resource.getURL());
// Image image = Image.getInstance("/Users/pdai/pdai/www/tech-pdai-spring-demos/481-springboot-demo-file-pdf-itextpdf/src/main/resources/pdai-guli.png");
image.setAlignment(Element.ALIGN_CENTER);
image.scalePercent(60); // 缩放
document.add(image);
// close
document.close();
return document;
}
private List userList = new ArrayList<>(); for (int i = 0; i < 5; i++) { userList.add(User.builder() .id(Long.parseLong(i + "")).userName("pdai" + i).email("pdai@pdai.tech" + i).phoneNumber(121231231231L) .description("hello world" + i) .build()); } return userList; } 复制代码 在完成时能够将如下创立文档内容的办法封装到Util工具类中
private Paragraph createTitle(String content) throws IOException, DocumentException { Font font = new Font(getBaseFont(), 24, Font.BOLD); Paragraph paragraph = new Paragraph(content, font); paragraph.setAlignment(Element.ALIGN_CENTER); return paragraph; }
private Paragraph createChapterH1(String content) throws IOException, DocumentException { Font font = new Font(getBaseFont(), 22, Font.BOLD); Paragraph paragraph = new Paragraph(content, font); paragraph.setAlignment(Element.ALIGN_LEFT); return paragraph; }
private Paragraph createChapterH2(String content) throws IOException, DocumentException { Font font = new Font(getBaseFont(), 18, Font.BOLD); Paragraph paragraph = new Paragraph(content, font); paragraph.setAlignment(Element.ALIGN_LEFT); return paragraph; }
private Paragraph createParagraph(String content) throws IOException, DocumentException { Font font = new Font(getBaseFont(), 12, Font.NORMAL); Paragraph paragraph = new Paragraph(content, font); paragraph.setAlignment(Element.ALIGN_LEFT); paragraph.setIndentationLeft(12); //设置左缩进 paragraph.setIndentationRight(12); //设置右缩进 paragraph.setFirstLineIndent(24); //设置首行缩进 paragraph.setLeading(20f); //行间距 paragraph.setSpacingBefore(5f); //设置段落上空白 paragraph.setSpacingAfter(10f); //设置段落下空白 return paragraph; }
public PdfPCell createCell(String content) throws IOException, DocumentException { PdfPCell cell = new PdfPCell(); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setHorizontalAlignment(Element.ALIGN_CENTER); Font font = new Font(getBaseFont(), 12, Font.NORMAL); cell.setPhrase(new Phrase(content, font)); return cell; }
private BaseFont getBaseFont() throws IOException, DocumentException { return BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); }
体系课-Java工程师2022版download:https://www.zxit666.com/5135/