需求:将一个html页面转成pdf格式。 2.方法:在实现之前先考虑一个问题,pdf是前端生成还是后端生成。这里采用pdfbox+itext(PDF文件名可自定义)技术在服务端生成。 优点:免费,不需要安转软件,速度快,对于开发者而言,开发
需求:将一个html页面转成pdf格式。
2.方法:在实现之前先考虑一个问题,pdf是前端生成还是后端生成。这里采用pdfbox+itext(PDF文件名可自定义)技术在服务端生成。
优点:免费,不需要安转软件,速度快,对于开发者而言,开发中仅需导入相应jar,且易部署。
缺点:对于html标签比较严格。
实现:
3.1 需要的jar
itext-2.0.8.jar+pdfbox-2.0.19.jar
2 准备好html页面代码(注意:这里需要手动指定字体):
sHtml += "]>";sHtml += "";sHtml += "";sHtml += "";sHtml += "";sHtml += "这里是测试PDF代码部分
";sHtml += "";sHtml += "";
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();} }
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) { }
完成!
来源地址:https://blog.csdn.net/qq_40852597/article/details/129502501
--结束END--
本文标题: java实现html转pdf
本文链接: https://www.lsjlt.com/news/377610.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-04-03
2024-04-03
2024-04-01
2024-01-21
2024-01-21
2024-01-21
2024-01-21
2023-12-23
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0