java编程将HTML文件转换成PDF文件
网上有好几种方法可以将将HTML文件转换成PDF文件但是有些对HTML文件格式要求比较严格,稍微错了一些就不能生成我们所要的PDF文件,这里我推荐一个
PD4ML,它可以解决HTML文件格式不正确的问题,可以生成一个比较好的PDF文件,其处理速度快,而且对CSS文件兼容的非常好。下面是最基本的
PD4ML编程:
package samples;import java.awt.Insets;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.InvalidParameterException;import org.zefer.pd4ml.PD4Constants;
import org.zefer.pd4ml.PD4ML;public class GettingStarted1 {protected int topValue = 10;protected int leftValue = 20;protected int rightValue = 10;protected int bottomValue = 10;protected int userSpaceWidth = 1300;public static void main(String[] args) {try {GettingStarted1 jt = new GettingStarted1();jt.doConversion("http://pd4ml.com/sample.htm", "c:/pd4ml.pdf");} catch (Exception e) {e.printStackTrace();}}public void doConversion( String url, String outputPath ) throws InvalidParameterException, MalformedURLException, IOException {File output = new File(outputPath);java.io.FileOutputStream fos = new java.io.FileOutputStream(output);PD4ML pd4ml = new PD4ML();pd4ml.setHtmlWidth(userSpaceWidth); // set frame width of "virtual web browser" // choose target paper format and "rotate" it to landscape orientationpd4ml.setPageSize(pd4ml.changePageOrientation(PD4Constants.A4)); // define PDF page marginspd4ml.setPageInsetsMM(new Insets(topValue, leftValue, bottomValue, rightValue)); // source HTML document also may have margins, could be suppressed this way // (PD4ML *Pro* feature):pd4ml.addStyle("BODY {margin: 0}", true);// If built-in basic PDF fonts are not sufficient or // if you need to output non-Latin texts,// TTF embedding feature should help (PD4ML *Pro*)pd4ml.useTTF("c:/windows/fonts", true);pd4ml.render(new URL(url), fos); // actual document conversion from URL to filefos.close();System.out.println( outputPath + "\ndone." );}
}
The following Java class slightly changes the above example. Now it pre-reads source HTML to a string and passes it torender()method wrapped toStringReader. First it writes PDF bytes toByteArrayOutputStream, which makes possible to measure size of the resulting document.
A disadvantage of the method is a bigger RAM utilization.
package samples;import java.awt.Insets;;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.InvalidParameterException;import org.zefer.pd4ml.PD4Constants;
import org.zefer.pd4ml.PD4ML;public class GettingStarted2 {protected int topValue = 10;protected int leftValue = 20;protected int rightValue = 10;protected int bottomValue = 10;protected int userSpaceWidth = 1300;public static void main(String[] args) {try {GettingStarted2 jt = new GettingStarted2();String html = readFile("c:/sample.htm", "UTF-8");jt.doConversion2(html, "c:/pd4ml.pdf");} catch (Exception e) {e.printStackTrace();}}public void doConversion2( String htmlDocument, String outputPath ) throws InvalidParameterException, MalformedURLException, IOException {PD4ML pd4ml = new PD4ML();pd4ml.setHtmlWidth(userSpaceWidth); // set frame width of "virtual web browser" // choose target paper formatpd4ml.setPageSize(pd4ml.changePageOrientation(PD4Constants.A4)); // define PDF page marginspd4ml.setPageInsetsMM(new Insets(topValue, leftValue, bottomValue, rightValue)); // source HTML document also may have margins, could be suppressed this way // (PD4ML *Pro* feature):pd4ml.addStyle("BODY {margin: 0}", true);// If built-in basic PDF fonts are not sufficient or // if you need to output non-Latin texts, TTF embedding feature should help // (PD4ML *Pro*)pd4ml.useTTF("c:/windows/fonts", true);ByteArrayOutputStream baos = new ByteArrayOutputStream();// actual document conversion from HTML string to byte arraypd4ml.render(new StringReader(htmlDocument), baos); // if the HTML has relative references to images etc, // use render() method with baseDirectory parameter insteadbaos.close();System.out.println( "resulting PDF size: " + baos.size() + " bytes" );// in Web scenarios it is a good idea to send the size with // "Content-length" HTTP headerFile output = new File(outputPath);java.io.FileOutputStream fos = new java.io.FileOutputStream(output);fos.write( baos.toByteArray() );fos.close();System.out.println( outputPath + "\ndone." );}private final static String readFile( String path, String encoding ) throws IOException {File f = new File( path );FileInputStream is = new FileInputStream(f);BufferedInputStream bis = new BufferedInputStream(is);ByteArrayOutputStream fos = new ByteArrayOutputStream();byte buffer[] = new byte[2048];int read;do {read = is.read(buffer, 0, buffer.length);if (read > 0) { fos.write(buffer, 0, read); }} while (read > -1);fos.close();bis.close();is.close();return fos.toString(encoding);}
}
java编程将HTML文件转换成PDF文件相关推荐
- Java使用aspse实现Excel文件转换成PDF文件
使用Java代码把Excel文件转换成PDF文件 需要引用aspose包,引入操作我写了一个博客,地址如下 https://blog.csdn.net/weixin_46713508/article/ ...
- 如何将Ai文件转换成PDF文件
要将Ai文件转换成PDF文件,请按照以下步骤操作: 1. 打开客汇宝网站软件并打开要转换的文件. 2. 点击"文件"菜单并选择"另存为". 3. 在" ...
- 怎么把图片文件转换成PDF文件
除了office文件外,我们最常用的就是PDF文件了.因为PDF文件格式可以将文字.字型.格式.颜色及独立于 设备和分辨率的图形图像等封装在一个文件中.该格式文件还可以包含超文本链接.声音和动态影像等 ...
- CAJ文件转换成PDF文件:教你如何实现文件格式转换
CAJ文件是中国知网常用的一种文献格式,但有时候我们需要将其转换成PDF格式,以方便阅读.打印.分享等用途.本文将教你如何实现CAJ文件转换成PDF文件. 方法一.使用CAJViewer软件 步骤1: ...
- 把jpg文件转换成pdf文件
把jpg文件转换成pdf文件 生涯中,人人常常会拍摄一些照片用来忖量,可是岁月长了,时时会由于照片多而杂乱而懒于翻看,那末你是否思虑做一个电子相册,或制造一本PDF花样的书本来翻看呢?业余的这款JPG ...
- 怎么把jpg文件转换成pdf文件
怎么把jpg文件转换成pdf文件 PDF转换成Word文档对我们来讲并不生僻,假设文字是由一张张图片构成的,碰着这种状况怎么办,怎么将JPG转换成PDF?菜鸟损耗了不少工夫和肉体才找到一款好用的JPG ...
- 怎么将知网下载的CAJ文件转换成PDF文件
我们熟知的CAJ文件必须使用中国知网的CAJ Viewer才能打开,但是如果想以PDF的格式查看论文那就需要将CAJ文件转换为pdf格式,那么怎么CAJ文件转换成PDF文件呢? 转换方法其实很简单,这 ...
- 怎么把caj文件转换成pdf文件
我们在网上下载素材的时候,就有很大一部分是caj格式的文件,我们又想将caj文件整理成pdf文件,那么怎么把caj文件转换成pdf文件呢? 其实转换很简单,只需要一个CAJ转换器就能实现,下面介绍ca ...
- 如何将CAJ文件转换成PDF文件?教你一招搞定
CAJ文件是中国知网的专用格式,主要用于存储学术文献等信息.由于这种格式并非常见格式,很多用户不知道如何打开或转换.如果您需要将CAJ文件转换成PDF文件,不必担心,您可以使用记灵在线工具来解决这个问 ...
最新文章
- Windows下开源缺陷跟踪系统mantis安装指南(续)-
- Android开发--Service开启,关闭,绑定,解除
- tf.sign和tf.reduce_sum
- RingtoneManager-获得系统当前的铃声
- 交换机入门配置:IP和远程登录功能
- 网站前端性能优化之javascript和css
- c# 实现MD5,SHA1,SHA256,SHA512等常用加密算法
- 2018年下半年《软件评测师》下午试卷及答案
- STM32的CAN过滤器详解
- Centos7 更换阿里yum源
- 数据寻址——偏移寻址
- linux桥接wifi与有线,两个路由器有线桥接好还是无线桥接好?
- 虚幻引擎(UE4)场景漫游交互项目制作
- Java 一元三次方程求解
- Rancher学习日记4
- python 线性回归函数_8种用Python实现线性回归的方法,究竟哪个方法最高效?
- 基于深度学习的目标检测算法综述(二)
- 你知道如何健康饮水吗
- 不可忽视的软件测试环境问题
- 大对象数据的访问控制 (2)
热门文章
- Kindle 可旋转桌面时钟
- Rasa课程、Rasa培训、Rasa面试、Rasa实战系列之 Countvectors and Spelling Errors
- 牛客网-《刷C语言百题》第三期
- 【SEED Labs 2.0】V*N Tunneling Lab
- 【jzoj2163】【二分】算法学习(sfxx)
- “秒杀系统“设计原理
- CDR X6设计师的福利,3折特惠!
- stm32USB之模拟U盘
- 企业微信 web 项目工业级蜕变
- 简单批处理文件使用win7自带wifi,妈妈再也不担心WiFi软件不稳定了