Java 可以通过 IText 直接把内容生成 pdf 文件,下面的 Demo 主要演示了文件属性、页眉页脚、表格、段落文字、图片的生成。
先上代码:

package html2PDF;import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;import com.lowagie.text.BadElementException;
import com.lowagie.text.Cell;
import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.HeaderFooter;
import com.lowagie.text.Image;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.Rectangle;
import com.lowagie.text.Table;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;public class CreatePdf {public static void main(String[] args) throws Exception {Document document = new Document();PdfWriter.getInstance(document, new FileOutputStream(new File("E:\\pdfTest\\mypdfdoc.pdf")));BaseFont baseFont = BaseFont.createFont("E:\\testFile\\msyh.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);// 文字如果要加粗,修改第三个参数Font msya = new Font(baseFont, 12, Font.NORMAL);//设置文档属性createAttr(document);//设置页眉页脚createHeaderFooter(document, msya);document.open();document.add(new Paragraph("Table 样例", msya));//创建表格及设置表格样式Table table = createTable(4, Element.ALIGN_CENTER, 2);//创建单元格并设置样式,看自身情况可使用循环table.addCell(createCell("姓名", msya));
//      table.addCell(createCell("性别", msya, Element.ALIGN_LEFT), Element.ALIGN_TOP);table.addCell(createCell("性别", msya));table.addCell(createCell("籍贯", msya));table.addCell(createCell("生日", msya));table.addCell(createCellWithSpan("行列合并", msya, 2, 2));table.addCell(createCell("英语", msya));table.addCell(createCell("数学", msya));table.addCell(createCell("生物", msya));
//      table.addCell(createCell("地理", msya));document.add(table);Paragraph parag = new Paragraph("  ----------------------这里是分割线---------------------    ", msya);parag.setAlignment(Element.ALIGN_CENTER);document.add(parag);Chunk chunk = new Chunk("PdfTable 样例", msya);
//      chunk.setHorizontalScaling(0.5f);  //水平缩放document.add(chunk);//创建表格及设置表格样式PdfPTable pTable = createPdfTabel();//创建单元格并设置样式,看自身情况可使用循环pTable.addCell(createPdfCell("姓名", msya));pTable.addCell(createPdfCell("性别", msya));pTable.addCell(createPdfCell("籍贯", msya));pTable.addCell(createPdfCell("生日", msya));pTable.addCell(createPdfCell("英语", msya));pTable.addCell(createPdfCell("数学", msya));pTable.addCell(createPdfCellWithSpan("行列合并", msya, 2, 1));pTable.addCell(createPdfCell("物理", msya));pTable.addCell(createPdfCell("化学", msya));pTable.addCell(createPdfCell("生物", msya));
//      pTable.addCell(createPdfCell("地理", msya));document.add(pTable);Phrase phrase = new Phrase("短语标题"); //未加入字体,不显示document.add(phrase);document.add(new Chunk("这里是块内容,这里是块内容,这里是块内容,这里是块内容,这里是块内容,"+ "这里是块内容,这里是块内容", msya));document.add(new Paragraph("这里是段落内容,这里是段落内容,这里是段落内容,这里是段落内容,"+ "这里是段落内容,这里是段落内容,这里是段落内容,这里是段落内容,这里是段落内容,这里是段落内容,"+ "这里是段落内容", msya));//生成图片document.add(imgToPdf("E:\\testfile\\money.jpg"));// 新建第二页,页眉页脚会继承,页码会递增document.newPage();
//      document.setPageSize(PageSize.A4);  //默认是 A4 大小document.add(new Paragraph("第二页", msya));document.close();System.out.println("over");}private static Image imgToPdf(String imgPath) {// 读取一个图片Image image = null;try {image = Image.getInstance(imgPath);} catch (Exception e) {e.printStackTrace();}image.setAlignment(Image.ALIGN_CENTER);// 设置图片的绝对位置// 第一个参数表示距页面左下角的横向宽度,第二个参数表示距页面左下角的纵向高度
//      image.setAbsolutePosition(0, 200);//不写这行则默认在内容下一行// 等比例放大或缩小图片
/*      float imageHeight = image.getScaledHeight();float imageWidth = image.getScaledWidth();int i = 0;while (imageHeight > 500 || imageWidth > 500) {image.scalePercent(100 - i);   //减 是缩小, 加 是放大i++;imageHeight = image.getScaledHeight();imageWidth = image.getScaledWidth();System.out.println("imageHeight->" + imageHeight);System.out.println("imageWidth->" + imageWidth);}
*/image.scaleAbsolute(50, 60);  //参数代表宽高,默认居中return image;}private static PdfPCell createPdfCellWithSpan(String content, Font msya, int rowSpan, int colSpan) {PdfPCell pCell = new PdfPCell();pCell.setColspan(rowSpan);pCell.setRowspan(colSpan);pCell.setHorizontalAlignment(Element.ALIGN_CENTER);pCell.setVerticalAlignment(Element.ALIGN_MIDDLE);pCell.setPhrase(new Phrase(content,msya));return pCell;}private static PdfPCell createPdfCell(String content, Font msya) {PdfPCell pCell = new PdfPCell();pCell.setVerticalAlignment(Element.ALIGN_MIDDLE);pCell.setHorizontalAlignment(Element.ALIGN_CENTER);pCell.setPadding(5);pCell.setPhrase(new Phrase(content,msya));return pCell;}private static PdfPTable createPdfTabel() {PdfPTable pTable = new PdfPTable(4);pTable.getDefaultCell().setBorder(1);pTable.setHorizontalAlignment(Element.ALIGN_CENTER);return pTable;}private static Cell createCellWithSpan(String content, Font msya, int rowSpan, int colSpan) {Cell cell = new Cell();if(rowSpan > 1) {cell.setRowspan(rowSpan);}else {cell.setRowspan(1);}if(colSpan > 1) {cell.setColspan(colSpan);}else {cell.setColspan(1);}cell.setHorizontalAlignment(Element.ALIGN_CENTER);cell.setVerticalAlignment(Element.ALIGN_MIDDLE);cell.add(new Phrase(content, msya));return cell;}private static Cell createCell(String content, Font msya) {Cell cell = new Cell();cell.setHorizontalAlignment(Element.ALIGN_CENTER);cell.setVerticalAlignment(Element.ALIGN_MIDDLE);cell.add(new Phrase(content, msya));return cell;}private static Cell createCell(String content, Font msya, int halign, int valign) {Cell cell = new Cell();cell.setHorizontalAlignment(halign);cell.setVerticalAlignment(valign);cell.add(new Phrase(content, msya));return cell;}private static Table createTable(int colNum, int align, int padding) {Table table = null;try {table = new Table(colNum);} catch (BadElementException e) {e.printStackTrace();}/** 外边框一直有* 0 单元格无边框;1 单元格有横边框;4的倍数 单元格有竖边框;5 横竖边框均有* 默认有横竖边框*/
//      table.getDefaultCell().setBorder(Cell.NO_BORDER);table.setAlignment(align);table.setPadding(padding);return table;}private static void createHeaderFooter(Document document, Font msya) {HeaderFooter header = new HeaderFooter(new Phrase("这里是页眉", msya), false);// 设置是否有边框等// header.setBorder(Rectangle.NO_BORDER);header.setBorder(Rectangle.BOTTOM);header.setAlignment(1);
//      header.setBorderColor(Color.red);document.setHeader(header);HeaderFooter footer = new HeaderFooter(new Phrase("——第", msya), new Phrase("页——", msya));/*** 0是靠左 1是居中 2是居右,或者直接用 Element 的常量属性*/footer.setAlignment(1);
//      footer.setAlignment(Element.ALIGN_RIGHT);
//      footer.setBorderColor(Color.red);footer.setBorder(Rectangle.BOX);document.setFooter(footer);}private static void createAttr(Document document) {document.addAuthor("xiao");document.addHeader("name", "content");document.addSubject("subject");document.addKeywords("keywords  keyword");document.addTitle("title");document.addCreator("creator");//  document.addProducer();//   document.addCreationDate();}
}

本博主有话说:

  1. Demo 用的是 itext-2.1.7.jar ,其中表格对比了 itextpdf-5.4.3.jar 中的 表格。jar 包自取不谢。戳我下载
  2. 看如下效果图,两种表格各有特点:
  • 看边框:itext 的表格的外边框比里面的边框粗,而 itextpdf 的表格的内外边框是一样粗细。我都没另外设置边框。
  • 看单元格内边距:我同样设置了单元格内容水平和垂直居中,但是 itext 的表格内容水平是居中了,但是垂直方向是偏下的。itextpdf 表格内容可以水平和垂直居中。
  • 看单元格合并:我试了两种表格同时合并2行2列,结果 itext 的表格可以正确显示效果,而 itextpdf 的表格报空指针错误了,程序都无法运行。(可能是我写的方式不对,如果哪位朋友有正确写法,让留言指导一下)
  • 看单元格内容:itext 的表格,即时我最后一个单元格没有添加,整个表格还是显示出来了,只是最后一个单元格的内容默认为空了。itextpdf 的表格同样我少添了一个单元格,程序没有报错,但是最后一整行都没有显示出来。
  1. 需要添加中文内容时,请务必带上字体,要不然不显示中文。
  2. 文章属性和页眉页脚等相关内容需要在 document.open() 前设置,否则无效。
  3. 内容超过一页会自动新建页面,也可手动在未满一页时新增页面。

效果图如下:

Java 生成 pdf相关推荐

  1. java 其他文件转pdf_java 其他文件转成pdf java生成pdf

    java生成pdf需要用到的包pd4ml.jar 下载地址:http://download.csdn.net/detail/yanning1314/7124741 package com.cular. ...

  2. java生成pdf方法_详解Java生成PDF文档方法|chu

    最近项目需要实现PDF下载的功能,由于没有这方面的经验,从网上花了很长时间才找到相关的资料.整理之后,发现有如下几个框架可以实现这个功能. 1. 开源框架支持iText,生成PDF文档,还支持将XML ...

  3. java实现pdf的生成下载打印,java生成pdf电子账单,java生成pdf合同模板

    最近公司要做个生成pdf电子账单凭证的功能,由于这个公司没有任何代码可借鉴,这个时候我就必须得自己搞明白具体的每一步应该怎么做,引什么jar包?用什么方式去实现?这篇博客中会给出从头到尾及其详细的代码 ...

  4. java生成PDF,各种格式、样式、水印都有

    需要的JAR包链接:https://www.langhuaquan.com/asset/search/JAVA生成PDF需要的JAR包/ 原文链接:https://www.langhuaquan.co ...

  5. java生成PDF 导出

    tip:生成pdf导出 需要的JAR包链接:https://www.hebaocun.com/asset/search/JAVA生成PDF需要的JAR包/ 原文链接:https://www.hebao ...

  6. iText5实现Java生成PDF文件完整版,二维码

    iText5实现Java生成PDF文件完整版 vue 项目中分别使用 vue-pdf 插件和内嵌 iframe 实现 PDF 文件预览,缩放,旋转,下载,保存等功能 ? Vue打印文件(v-print ...

  7. Java生成PDF文档 iText使用PDF模板一

    最近在弄这个java生成pdf,哎,在网上查找了各种各样的学习资料,弄了几天,今天终于把这个效果简单的弄出来,所以,也把这个,我所走过的坑,作一个记录,提供接下来需要学习的人. 参考文献文档:http ...

  8. java 生成 pdf html转pdf 支持 中文 自定义模板

    java 生成pdf DEMO 开发过程中遇到的坑 /** * 切记 css 要定义在head 里,否则解析失败 * css 要定义字体 * 字体中英文 https://www.cnblogs.com ...

  9. java实现保存合同模板_java实现pdf的生成下载打印,java生成pdf电子账单,java生成pdf合同模板...

    最近公司要做个生成pdf电子账单凭证的功能,由于这个公司没有任何代码可借鉴,这个时候我就必须得自己搞明白具体的每一步应该怎么做,引什么jar包?用什么方式去实现?这篇博客中会给出从头到尾及其详细的代码 ...

  10. Adobe Acrobat pro生成PDF模版 java生成PDF

    最近做了一个关于动态生成PDF合同的需求  java生成PDF 网络上随便一搜遍有了 不要用手动在代码里面输入合同中的文字这种方式 如这样的方式 http://blog.csdn.net/justin ...

最新文章

  1. EF-Linq将查询结果转换为Liststring
  2. 使用grep 在源码文件查找特定字符串
  3. MongoDB同步到Oracle,MongoToOracleMongoDB数据库迁移工具
  4. SAP ABAP Soap测试框架一些有用的工具类
  5. LwIP应用开发笔记之七:LwIP无操作系统HTTP服务器
  6. 数据结构c语言课程设计报告,数据结构c语言课程设计报告.doc
  7. 实现微信聊天机器人-初级篇
  8. 如何免费将网页内容转成Word文档
  9. 4和2大于号小于号箭头那边_‘’口诀化‘’教学之二――大于号和小于号
  10. MySQL 临时目录
  11. 关于eslint误报Unexpected side effect in “getCheckedData“ computed property的问题
  12. SECCON-CTF-2014-Decrypt-It-easy
  13. 《与熊共舞》第一章--逆“风”而行
  14. ebay测评补单需要注意哪些?
  15. 数据库开发工程师转行大数据开发可以吗?
  16. iOS14iCloud云盘为何删除文稿和数据不好用_5个特征选择算法,让你的数据处理得心应手...
  17. 给企业划分子网(子网划分)
  18. windows xp 定时执行任务(一)
  19. com.sun.proxy.$Proxy0 cannot be cast to ** 解决方法
  20. Android自定义控件——仿微信语音按钮

热门文章

  1. 我的物联网项目(十) 线下之战
  2. WebOffice使用二
  3. 抽签小程序(C语言随机数),随机数生成器
  4. 【计算机毕业设计】基于微信小程序的校园快递代领平台
  5. 旺旺模块的操作(联系客服)
  6. 【国内某社交软件的加解密分析】
  7. LightOJ 1198
  8. GB/T 17626.2-2018下载网址
  9. 翻译——奇偶校验矩阵和低密度奇偶校验码的构造方法
  10. Javaweb(AJAX快速入门)