PdfBox读取PDF加载pdf文件出错

  • 下载相关Jar包(pdfbox和fontbox为主)
    网址http://pdfbox.apache.org/download.cgi

  • 准备pdf格式文件(代码创建)

package com.unify.service;import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType1Font;public class createHelloPDF {public static void createPdf(){ PDDocument doc = null;PDPage page = null;try {doc = new PDDocument();page = new PDPage();doc.addPage(page);PDFont font = PDType1Font.HELVETICA_BOLD;PDPageContentStream content = new PDPageContentStream(doc, page);content.beginText();content.setFont(font, 12);content.moveTextPositionByAmount(100, 700);String txt = "道可道,非常道;名可名,非常名。"+"无名,万物之始,有名,万物之母。"+"故常无欲,以观其妙,常有欲,以观其徼。"+"此两者,同出而异名,同谓之玄,玄之又玄,众妙之门。";content.drawString(txt);content.endText();content.close();doc.save("C:\\Users\\admin\\Downloads\\crt.pdf");doc.close();} catch (Exception e) {System.out.println(e);}}public static void main(String[] args) {createPdf();System.err.println("success");}
}

执行,报错:

13566833-b92708da47a7895e.png

PdfBox不支持中文.png

修改String txt内容为英文;

String txt = "Faith can move mountains";

执行代码,生成相应pdf文件至相应目录。

  • 利用PdfBox读取PDF内容,代码如下:
package com.unify.service;import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;import org.apache.pdfbox.io.RandomAccessBuffer;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;public class PdfReader {static void ReadTxt(String path,int startPage,int endPage){File pdfFile = new File(path);boolean aa = pdfFile.canRead();System.err.println("检验是否可读---"+aa);PDDocument document = null;try{System.err.println("准备加载");// 方式一:
//        InputStream input = null;
//        input = new FileInputStream( pdfFile );
//        //加载 pdf 文档
//        PDFParser parser = new PDFParser(new RandomAccessBuffer(input));
//        parser.parse();
//        document = parser.getPDDocument();// 方式二document=PDDocument.load(pdfFile);// 获取页码int pages = document.getNumberOfPages();System.err.println("该PDF一共有-"+pages+"页");//读文本内容PDFTextStripper stripper=new PDFTextStripper();// 设置按顺序输出stripper.setSortByPosition(true);stripper.setStartPage(startPage);stripper.setEndPage(endPage);String content = stripper.getText(document);System.out.println(content);     }catch(Exception e){System.out.println(e);}}
}
package com.unify.service;public class Test {public static void main(String[] args) {PdfReader.ReadTxt("C:\\Users\\admin\\Downloads\\crt.pdf",1,2);System.err.println("阅读结束");}
}
// 执行Test

执行结果:

13566833-741af06a6dabb345.png

输出阅读内容.png

新换一个PDF试试,比如唐诗三百首:

13566833-68194ba539741c44.png

加载文档出错.png

查阅相关资料,可知PdfBox不支持中文,我们换一种方式进行PDF操作,通过itex插件进行pdf的生成和解析:

通过itex插件操作PDF

需要的jar包括以下几个:

13566833-93ec8101724c66f9.jpg

itex插件所需Jar包.jpg

下载链接:https://download.csdn.net/download/weixin_39309402/10878446

建一个简单model为User.java,代码:

package com.xf.itex;public class User {private String name;    //姓名private int age ;       //年龄private int height; //身高private String adress;  //住址private String sex;     //性别private String love;    //爱好// getter和setter方法略
}

路径判断类:

package com.xf.itex;import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;public class GenerateFold{/*** 判断路径是否存在 存在则用 不存在则创建* @param foldName  保存路径* @return          需要保存路径*/public  String getFold(String foldName){SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");String todayStr = format.format(Calendar.getInstance().getTime());String foldPath = foldName + File.separator + todayStr; File file = new File(foldPath);if(!file.exists() && !file.isDirectory()){System.out.println("不存在");file.mkdirs();}else{System.out.println("存在");}return  foldPath;}
}

文件名创建:

package com.xf.itex;import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.UUID;/*** 生成文件名*/
public class GenerateFileName{/*** 规则是:文件目录/生成时间-uuid(全球唯一编码).文件类别* @param fileDir  文件的存储路径* @param fileType 文件的类别* @return                 文件的名字  */public String generateFileName(String fileDir,String fileType){String saveFileName = "";SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSS");saveFileName += format.format(Calendar.getInstance().getTime());UUID uuid = UUID.randomUUID();  //全球唯一编码saveFileName += "-" + uuid.toString();saveFileName += "." + fileType;saveFileName = fileDir + File.separator + saveFileName;return saveFileName;}
}

创建表格Pdf代码:

package com.xf.itex;import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.PageSize;
import com.lowagie.text.Phrase;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;/*** 生成pdf* */
public class CreatePdf{Document document = new Document();// 建立一个Document对象private static Font headfont;// 设置字体大小private static Font keyfont;// 设置字体大小private static Font textfont;// 设置字体大小static{//中文格式BaseFont bfChinese;try{// 设置中文显示bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);headfont = new Font(bfChinese, 10, Font.BOLD);// 设置字体大小keyfont = new Font(bfChinese, 8, Font.BOLD);// 设置字体大小textfont = new Font(bfChinese, 8, Font.NORMAL);// 设置字体大小}catch (Exception e){e.printStackTrace();}}/*** 文成文件* @param file 待生成的文件名*/public CreatePdf(File file){document.setPageSize(PageSize.A4);// 设置页面大小try{PdfWriter.getInstance(document, new FileOutputStream(file));document.open();}catch (Exception e){e.printStackTrace();}}public CreatePdf(){}public void initFile(File file){document.setPageSize(PageSize.A4);// 设置页面大小try{PdfWriter.getInstance(document, new FileOutputStream(file));document.open();}catch (Exception e){e.printStackTrace();}}int maxWidth = 520;/*** 为表格添加一个内容* @param value           值* @param font            字体* @param align            对齐方式* @return                添加的文本框*/public PdfPCell createCell(String value, Font font, int align){PdfPCell cell = new PdfPCell();cell.setVerticalAlignment(Element.ALIGN_MIDDLE);cell.setHorizontalAlignment(align);cell.setPhrase(new Phrase(value, font));return cell;}/*** 为表格添加一个内容* @param value           值* @param font            字体* @return                添加的文本框*/public PdfPCell createCell(String value, Font font){PdfPCell cell = new PdfPCell();cell.setVerticalAlignment(Element.ALIGN_MIDDLE);cell.setHorizontalAlignment(Element.ALIGN_CENTER);cell.setPhrase(new Phrase(value, font));return cell;}/*** 为表格添加一个内容* @param value           值* @param font            字体* @param align            对齐方式* @param colspan        占多少列* @return                添加的文本框*/public PdfPCell createCell(String value, Font font, int align, int colspan){PdfPCell cell = new PdfPCell();cell.setVerticalAlignment(Element.ALIGN_MIDDLE);cell.setHorizontalAlignment(align);cell.setColspan(colspan);cell.setPhrase(new Phrase(value, font));return cell;}/*** 为表格添加一个内容* @param value           值* @param font            字体* @param align            对齐方式* @param colspan        占多少列* @param boderFlag        是否有有边框* @return                添加的文本框*/public PdfPCell createCell(String value, Font font, int align, int colspan,boolean boderFlag){PdfPCell cell = new PdfPCell();cell.setVerticalAlignment(Element.ALIGN_MIDDLE);cell.setHorizontalAlignment(align);cell.setColspan(colspan);cell.setPhrase(new Phrase(value, font));cell.setPadding(3.0f);if (!boderFlag){cell.setBorder(0);cell.setPaddingTop(15.0f);cell.setPaddingBottom(8.0f);}return cell;}/*** 创建一个表格对象* @param colNumber  表格的列数* @return              生成的表格对象*/public PdfPTable createTable(int colNumber){PdfPTable table = new PdfPTable(colNumber);try{table.setTotalWidth(maxWidth);table.setLockedWidth(true);table.setHorizontalAlignment(Element.ALIGN_CENTER);table.getDefaultCell().setBorder(1);}catch (Exception e){e.printStackTrace();}return table;}public PdfPTable createTable(float[] widths){PdfPTable table = new PdfPTable(widths);try{table.setTotalWidth(maxWidth);table.setLockedWidth(true);table.setHorizontalAlignment(Element.ALIGN_CENTER);table.getDefaultCell().setBorder(1);}catch (Exception e){e.printStackTrace();}return table;}public PdfPTable createBlankTable(){PdfPTable table = new PdfPTable(1);table.getDefaultCell().setBorder(0);table.addCell(createCell("", keyfont));table.setSpacingAfter(20.0f);table.setSpacingBefore(20.0f);return table;}public <T> void generatePDF(String [] head,List<T> list,int colNum) {Class classType = list.get(0).getClass();// 创建一个只有5列的表格PdfPTable table = createTable(colNum);// 添加备注,靠左,不显示边框table.addCell(createCell("APP信息列表:", keyfont, Element.ALIGN_LEFT, colNum,false));//设置表头for(int i = 0 ; i < colNum ; i++){table.addCell(createCell(head[i], keyfont, Element.ALIGN_CENTER));}if(null != list && list.size() > 0){int size = list.size();for(int i = 0 ; i < size ; i++){T t = list.get(i);for(int j = 0 ; j < colNum ; j ++){//获得首字母String firstLetter = head[j].substring(0,1).toUpperCase(); //获得get方法,getName,getAge等String getMethodName = "get" + firstLetter + head[j].substring(1);Method method;try{//通过反射获得相应的get方法,用于获得相应的属性值method = classType.getMethod(getMethodName, new Class[]{});try{System.out.print(getMethodName +":" + method.invoke(t, new Class[]{}) +",");//添加数据table.addCell(createCell(method.invoke(t, new Class[]{}).toString(), textfont));}catch (IllegalArgumentException e){e.printStackTrace();}catch (IllegalAccessException e){e.printStackTrace();}catch (InvocationTargetException e){e.printStackTrace();}  }catch (SecurityException e){e.printStackTrace();}catch (NoSuchMethodException e){e.printStackTrace();}}System.out.println("");}}try{//将表格添加到文档中document.add(table);}catch (DocumentException e){e.printStackTrace();}//关闭流document.close();}/*** 提供外界调用的接口,生成以head为表头,list为数据的pdf* @param head  //数据表头* @param list  //数据* @return        //excel所在的路径*/public <T> String generatePDFs(String [] head,List<T> list){final String FilePath = "pdfPath";String saveFilePathAndName = "";//获得存储的根目录String savePath = "F:\\Temp";//获得当天存储的路径,不存在则生成当天的文件夹String realSavePath = new GenerateFold().getFold(savePath);saveFilePathAndName = new GenerateFileName().generateFileName(realSavePath,"pdf");File file = new File(saveFilePathAndName);try{file.createNewFile();}catch (IOException e1){e1.printStackTrace();}initFile(file);try{file.createNewFile();  //生成一个pdf文件}catch (IOException e){e.printStackTrace();}new CreatePdf(file).generatePDF(head,list,head.length);return saveFilePathAndName;}}

测试Test类:

package com.xf.itex;import java.util.ArrayList;
import java.util.List;public class Test {public static void main(String[] args) {System.out.println("begin");String [] head = {"name","age","height","adress","sex","love"};List<User> list = new ArrayList<User>();User user1 = new User("李逍遥",21,185,"渔村","男","打架");User user2 = new User("林月如",18,177,"南武林","女","打架");list.add(user1);list.add(user2);String filePath = new CreatePdf().generatePDFs(head,list);System.out.println(filePath);System.out.println("end");}
}
13566833-ca2f3f842698856a.png

创建pdf成功.png

13566833-6c65c09f42166c88.png

pdf内容.png

成功!有时间再写其他

Java生成PDF表格相关推荐

  1. java生成pdf表格_java在pdf中生成表格的方法

    1.目标 在pdf中生成一个可变表头的表格,并向其中填充数据.通过泛型动态的生成表头,通过反射动态获取实体类(我这里是User)的get方法动态获得数据,从而达到动态生成表格. 每天生成一个文件夹存储 ...

  2. java生成pdf表格示例代码

    使用itext代码直接生成pdf文件 用到jar包       itextpdf-5.2.1.jar   itext-asian-5.2.0.jar 优缺点 优点:生成快,代码直接能用 缺点:代码要写 ...

  3. java 生成PDF表格,添加页码,加盖水印(包括图片水印和文字水印)

    最近公司要求后端实现PDF导出功能,并且还要要求能够加盖水印.网上搜寻了一下,大多帖子比较老旧,并且随着开发包的版本更新,都不能用,所以有了这篇博客. 生成PDF所用到的jar包主要是itext,现在 ...

  4. Java—将数据生成pdf表格

    由于时间问题,所以粗略的封装了一个生成pdf表格的工具包(不喜欢讲废话,直接上代码!!!) package com.sgcc.dlsc.jibei.commons.utils;import com.i ...

  5. Java生成PDF文档(表格)

    Java生成PDF文档(表格) package org.jeecg.modules.esi.utils;import com.itextpdf.text.*; import com.itextpdf. ...

  6. java生成PDF(图片,模板,表格)

    刚接到了一个需求,生成一个pdf,一开始以为挺简单的,通过模板生成嘛,我也发过相应的文章,根据模板直接生成pdf,响应到前端或者根据模板生成pdf,直接指定下载位置,这两种方案都可以,不过这篇文章主要 ...

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

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

  8. java 生成word表格

    JAVA生成WORD文件的方法目前有以下种: 一种是jacob 但是局限于windows平台 往往许多JAVA程序运行于其他操作系统 在此不讨论该方案.(需要下载jacob.jar以及jacob.dl ...

  9. java生成PDF 导出

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

最新文章

  1. python学习第四课
  2. 【STM32】OLED 显示实验代码详解
  3. Java中9大内置基本数据类型Class实例和数组的Class实例
  4. python如何用xpath爬取指定内容_Python利用Xpath选择器爬取京东网商品信息
  5. HTML5教程:1.3 HTML 5的使用理由和待解决问题
  6. python的sorted排序具体解释
  7. Table of Contents
  8. 新手必读——OOP三大特征及联系
  9. 计算思维在计算机科学中的应用,计算思维在离散数学中的应用.pdf
  10. c语言运算符大全极其意义,C语言运算符大全
  11. 轻量级云服务器部署K3S(公网部署)
  12. cissp怎么维持?cissp维持费用多少?
  13. 基于LSTM自动生成中文藏头诗
  14. 为什么c语言加法错误,分数的加减法——C语言初学者代码中的常见错误与瑕疵(12)...
  15. 问题沟通以及反馈的原则 - BEST
  16. .*? 和 .*的区别
  17. 【图解UDS】UDS汽车诊断标准协议(ISO 14229)带你入门到精通
  18. 自动查找优惠券机器人(收藏)
  19. [每周心学]浙江大学公开课:王阳明心学
  20. 类别(Category)的作用(三)---添加非正式协议

热门文章

  1. 打印机扫描文档和照片
  2. 零基础学习C++系列课程(五) 持续更新中
  3. MoveNet-谷歌轻量级人体姿态估计算法
  4. css任意高度收缩动画技术
  5. 利用js随机数,写了一个随机点名的简单代码
  6. 垂直同步、三重缓冲、freesync
  7. xss and ssrf bypass 小tips
  8. 批量将doc转为docx
  9. python-数据库开发
  10. 【JS】1339- 一文搞懂 JS 原型链的来龙去脉