java实现html转pdf

您所在的位置:网站首页 pdf转化html java实现html转pdf

java实现html转pdf

2023-03-20 13:48| 来源: 网络整理| 查看: 265

1.需求:将一个html页面转成pdf格式。 2.方法:在实现之前先考虑一个问题,pdf是前端生成还是后端生成。这里采用pdfbox+itext(PDF文件名可自定义)技术在服务端生成。 优点:免费,不需要安转软件,速度快,对于开发者而言,开发中仅需导入相应jar,且易部署。 缺点:对于html标签比较严格。

3.实现: 3.1 需要的jar itext-2.0.8.jar+pdfbox-2.0.19.jar

3.2 准备好html页面代码(注意:这里需要手动指定字体):

sHtml += ""; sHtml += ""; sHtml += ""; sHtml += ""; sHtml += ""; sHtml += "这里是测试PDF代码部分"; sHtml += ""; sHtml += "";

3.3 服务端开始生成PDF文件:

public static void toPdf(String sHtml) { try { //创建PDf文件 ITextRenderer renderer = new ITextRenderer(); ITextFontResolver fontResolver = renderer.getFontResolver(); //C:/WINDOWS/Fonts/SimSun.ttc 系统自带的语言包,直接引用 fontResolver.addFont("C:/WINDOWS/Fonts/SimSun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); fontResolver.addFont("C:/WINDOWS/Fonts/Arial.ttf",BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);// 宋体字 String sDate = new SimpleDateFormat("yyyyMMdd").format(new Date()); String sTime = new SimpleDateFormat("HHmmssSSS").format(new Date()); //指定文件存放路径 URL sUrlPath = 当前类名.class.getResource("/"); String sPath = sUrlPath.toURI().getPath(); sPath1 = sPath.replace("WEB-INF/classes/", ""); String sPathFolder = sPath+sDate+"\\"; File filePath = new File(sPathFolder); if(!filePath.exists() && !filePath.isDirectory()){ filePath.mkdirs(); } String sFileName = sDate+sTime+".pdf"; String sPathSave = sPathFolder+sFileName; OutputStream os = new FileOutputStream(sPathSave); //使用有setDocumentFromString()方法的jar包 renderer.setDocumentFromString(sHtml); renderer.layout(); renderer.createPDF(os); os.close(); } catch (Exception e) { e.printStackTrace(); } }

3.4 前端页面发起请求,服务端将生成的PDF文件返回。

String sTitle = "测试PDF文件名"; File file = new File(sFileUrl);//这里的sFileUrl即上面PDF保存路径 try { OutputStream outputStream = response.getOutputStream(); //加载pdf附件到PDF流中 PDDocument document = PDDocument.load(new FileInputStream(file)); response.reset(); response.setContentType("application/pdf;charset=UTF-8"); response.setHeader("Content-Disposition", "inline;filename=" + URLEncoder.encode(sTitle, "UTF-8")); response.setContentType("application/pdf;charset=UTF-8"); //从PDF流中获得PDF文档属性对象 PDDocumentInformation info = document.getDocumentInformation(); //设置PDF文档属性对象的文件名称(最重要的环节) info.setTitle(sTitle); document.setDocumentInformation(info); //修改完直接输出到响应体中 document.save(outputStream); outputStream.close(); document.close(); out.clear(); out = pageContext.pushBody(); } catch (Exception e) { }

完成!



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3