html导出pdf的四种⽅式将html页⾯导出为pdf⽂件并打印,可以直接在windows下使⽤Ctrl + P,苹果下⌘ + P。
如果需要⽤代码实现,可以考虑jsPDF、iText、wkhtmltopdf等⽅式。
以下是三种⽅式代码对⽐:
⽅式优点缺点分
特殊字
符、样式
jsPDF 1、整个过程在客户端执⾏(不需要服务
器参与),调⽤简单
1、⽣成的pdf为图⽚形式,且内容失真⽀
不⽀
⽀持
iText 1、功能基本可以实现,⽐较灵活2、⽣
成pdf质量较⾼
1、对html标签严;格,少⼀个结束标签就会报错;
2、后端实现复杂,服务器需要安装
字体;3、图⽚渲染⽐较复杂(暂时还没解决)
⽀持
⽀持
wkhtmltopdf 1、调⽤⽅式简单(只需执⾏⼀⾏脚本);
2、⽣成pdf质量较⾼
1、服务器需要安装wkhtmltopdf环境;
2、根据⽹址⽣成pdf,对于有权限控制的页⾯需要
在进⾏处理
⽀持
⽀持
从实⽤和质量综合考虑,个⼈推荐使⽤iText。⽣成各种票据等⽂件质量好,代码也并不复杂。
以下是我使⽤三种⽅式测试的例⼦,IDE使⽤IDEA,Spring Boot结合Freemarker。
1.iText
iText是⼀个第三⽅报表java插件,可以在后端利⽤java随意⽣成、转化pdf⽂件,提供了很多api,⽐较灵活。
<!--PDF-->
<dependency>
<groupId&lipse.birt.runtime.3_7_1</groupId>
<artifactId></artifactId>
<version>2.1.7</version>
</dependency>
<dependency>
<groupId>org.xhtmlrenderer</groupId>
<artifactId>flying-saucer-pdf</artifactId>
<version>9.0.8</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.4.2</version>
</dependency>
<!--PDF end-->
使⽤iText需要下载字体⽂件
/**
* iText⽣成PDF 需要字体⽀持
*
* @param args
* @throws IOException
* @throws DocumentException
*/
public static void main(String[] args) throws IOException, DocumentException {
ITextRenderer renderer = new ITextRenderer();
ITextFontResolver fontResolver = FontResolver();
fontResolver.addFont("E:/下载/", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
OutputStream os = new FileOutputStream("E:/create/" + UUID.randomUUID() + ".pdf");
String htmlstr = "<!DOCTYPE html>\n" +
"<html lang=\"en\">\n" +
"<head>\n" +
"    <title>Title</title>\n" +
"</head>\n" +
"<body>\n" +
"<table border=\"1\">\n" +
"    <tr>\n" +
"        <td>row 1, cell 1</td>\n" +
"        <td>row 1, cell 2</td>\n" +
"    </tr>\n" +
"    <tr>\n" +
"        <td>row 2, cell 1</td>\n" +
"        <td>row 2, cell 2</td>\n" +
"    </tr>\n" +
"</table>\n" +
"</body>\n" +
"</html>";
renderer.setDocumentFromString(htmlstr);
renderer.layout();
}
使⽤Itext可以⽅便的根据写好的html模板来填充内容,设置标题页眉添加背景图⽚等操作。
2.jsPDF
⽣成效果并不是很好,但是⽆需后台服务器⽀持,操作简单
<!DOCTYPE>
<html>
<head>
<title>
html2canvas example
</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style type="text/css">
body {
margin: 0;
padding: 0;
background-color: white;
}
header, section {
overflow: hidden;
}
ul {
margin: 0;
border: 0;
padding: 0;
}
li {
display: block; /* i.e., suppress marker */
color: black;
height: 4em;
width: 25%;
margin: 0;
float: left;
background-color: green;
text-align: center;
line-height: 4em;
}
aside {
width: 20%;
float: left;
text-align: center;
}
aside a {
display: block;
height: 4em;
color: blue;
}
article {
padding: 2em 0;
width: 80%;
float: left;
}
</style>
</head>
<body>
<header>
<nav>
<ul>
<li>one</li>
<li>two</li>
<li>three</li>
<li>four</li>
</ul>
</nav>
</header>
<section>
<aside>
<h3>it is a title</h3>
<a href="">Stone Giant</a>
<a href="">link2</a>
<a href="">link3</a>
<a href="">link4</a>
<a href="">link5</a>
<a href="">link6</a>
</aside>
<article>
<img src="./img/Stone.png">
<button id="renderPdf">DOWNLOAD PDF</button>
<h2>Stone Giant</h2>
<p>
Coming to life as a chunk of stone, Tiny's origins are a mystery on which he continually speculates. He is a Stone Giant now, but what did he used to be? A splinter broken from a Golem's heel? A shard swept from a gargoyle-sculptor </p>
<p>
以⼀团⽯头的形式出现的⽣命体,⼩⼩不断思索他的起源,但这始终是个谜。现在的他是个⽯巨⼈,但过去是什么呢?从⼟傀儡的脚后跟掉落的碎⽚?从制造⽯像⿁的⼯房被打扫出来的碎屑?神圣预⾔⽯的表层之砂?受到强烈的好奇⼼驱</p>
<img src="./img/Spectre.jpg">
<h2>Spectre</h2>
<p>
Just as higher states of energy seek a lower level, the Spectre known as Mercurial is a being of intense and violent energy who finds herself irresistibly drawn to scenes of strife as they unfold in the physical world. While her normal sp </p>html document是什么
<p>
和所有强⼤的能量都喜欢欺凌弱⼩⼀样,被称为墨丘利的幽⿁也是⼀个拥有着强横能量的存在,同样的,她对现实世界中的冲突和纷争⽆⽐着迷。然⽽她平时的幽⿁形态超越了常⼈的感知范围,因此每当她以实体形态出现时,她不得不损</p>
<img src="./img/Ancient%20Apparition.jpg">
<h2>Ancient Apparition</h2>
<p>
Kaldr, the Ancient Apparition, is an image projected from outside time. He springs from the cold, infinite void that both predates the universe and awaits its end. Kaldr is, Kaldr was, Kaldr and what we perceive, powerful as it </p>
<p>
卡德尔,极寒幽魂,是时光之外的冰冷投影。他来⾃寒冷的⽆尽虚空,⽬睹宇宙诞⽣,见证宇宙终结。卡德尔是⼣在,今在,永在的⽆上⼒量...我们的所有认知,所有⾃认为正确的强⼤的事物,在永恒的卡德尔看来,不过是最细微最⽆⼒</p>
<img src="./img/weaver.jpg">
<h2>Weaver</h2>
<p>
The fabric of creation needs constant care, lest it grow tattered; for when it unravels, whole worlds come undone. It is the work of the Weavers to keep the fabric tight, to repair worn spots in the mesh of reality. They also defend from t </p>
<p>
创世之纱需要长期细⼼的照料,以防⽌其变得残破;因为⼀旦它散开了,整个世界就将毁于⼀旦。编织者的⼯作就是保持创世之纱的紧密,⽤现实之⽹修补它的破损。他们同样要防⽌那些在创世之纱的缺⼝上产卵或者侵蚀创世之纱的⾍⼦</p>
<img src="./img/Doom%20Bringer.jpg">
<h2>Doom Bringer</h2>
<p>
A towering being of unimaginable evil, Lucifer the Doom Bringer marches the farthest reaches of the world in search of new and exciting ways to satisfy his taste for unrest and greed. Once a feared leader in the army of the Purgers of
</p>
<p>
⼀个邪恶程度超乎想象的存在——末⽇使者路西法在世界各地不停寻着新的⽅法来满⾜他的贪婪和对骚乱的热衷。他曾经是其所在国度中备受畏惧的灭劫军团统帅,然⽽末⽇使者后来却离开了他的将军职位,丢下了⼀帮恶魔战⼠,原因</p>
<img src="./img/Dragon%20Knight.jpg">
<h2>Dragon Knight</h2>
<p>
After years on the trail of a legendary Eldwurm, the Knight Davion found himself facing a disappointing foe: the dreaded Slyrak had grown ancient and frail, its wings tattered, its few remaining scales stricken with scale-rot, its fangs gro </p>
<p>
在传说中的龙冢——厄尔多姆试炼多年以后,骑⼠戴维安发现⾃⼰的对⼿愈发不能令他满意了:过去那个让⼈闻风丧胆的神龙斯莱瑞克已经变得苍⽼⽽脆弱,它的双翼已经残破,它所剩不多的龙鳞也开始腐烂,它的⽖⼦变得肿⼤⽼化,它</p>
<img src="./img/Venomancer.jpg">
<h2>Venomancer</h2>
<p>
In the Acid Jungles of Jidi Isle, poison runs in the veins and bubbles in the guts of every creature that scuttles, climbs or swoops between fluorescent vines dripping with caustic sap. Yet even in this toxic menagerie, Venomancer is a </p>
<p>
在基迪岛上的浓酸密林中,在所有⽣物的体内,包括植物的根茎,动物的内脏中,都流淌着致命的腐蚀剧毒。然⽽,就算在这种毒巢⾥,剧毒术⼠也是公认的万毒之王。多年以前,⼀个叫做⾥瑟尔的植物学家乘坐⼩⾈跨越弗拉基海湾,想</p>
<img src="./img/Beast%20Master.jpg">
<h2>Beast Master</h2>
<p>
Karroch was born a child of the stocks. His mother died in childbirth; his father, a farrier for the Mad King of Slom, was trampled to death when he was five. Afterward Karroch was indentured to the king’s menagerie, where he grew up </p>
<p>
卡洛克⾃出⽣伊始就被当做兽婴。他的母亲在他出⽣时就死去;他的⽗亲是狂王斯洛姆的马蹄铁匠,在他五岁时被马践踏致死。后来,卡洛克将⾃⼰卖到国王的动物园⼲活,在那⾥,他和宫廷⾥⾯饲养的狮⼦,猩猩,野⿅以及其他⼀些</p>
<img src="./img/Dark%20Seer.jpg">
<h2>Dark Seer</h2>
<p>
Fast when he needs to be, and a cunning strategist, Ish'Kafel the Dark Seer requires no edged weapons to vanquish his enemies, relying instead on the strength of his powerful mind. His talent lies in his ability to maneuver the fight to </p>
<p>
迅捷如风,⾜智多谋,⿊暗贤者依什卡菲尔并不需要多么锋利的武器来搏⽃,他总是运⽤强⼤的⼼灵之⼒来征服敌⼈。他有着颠覆战局使之对⼰⽅有利的天才。迎着欢呼和敬意,他从⼀个叫做“幻墙之末”的世界⾛了出来,并不热衷于这个世</p>
</article>
</section>
<footer>write by linwalker @2017</footer>
<script type="text/javascript" src="./js/html2canvas.js"></script>
<script type="text/javascript" src="./js/jsPdf.debug.js"></script>
<script type="text/javascript">
var downPdf = ElementById("renderPdf");
html2canvas(document.body, {
onrendered:function(canvas) {
var contentWidth = canvas.width;
var contentHeight = canvas.height;
/
/⼀页pdf显⽰html页⾯⽣成的canvas⾼度;
var pageHeight = contentWidth / 595.28 * 841.89;
//未⽣成pdf的html页⾯⾼度
var leftHeight = contentHeight;
//pdf页⾯偏移
var position = 0;
//a4纸的尺⼨[595.28,841.89],html页⾯⽣成的canvas在pdf中图⽚的宽⾼
var imgWidth = 555.28;
var imgHeight = 555.28/contentWidth * contentHeight;
var pageData = DataURL('image/jpeg', 1.0);
var pdf = new jsPDF('', 'pt', 'a4');
/
/有两个⾼度需要区分,⼀个是html页⾯的实际⾼度,和⽣成pdf的页⾯⾼度(841.89)
//当内容未超过pdf⼀页显⽰的范围,⽆需分页
if (leftHeight < pageHeight) {
pdf.addImage(pageData, 'JPEG', 20, 0, imgWidth, imgHeight );
} else {
while(leftHeight > 0) {
pdf.addImage(pageData, 'JPEG', 20, position, imgWidth, imgHeight)
leftHeight -= pageHeight;
position -= 841.89;
//避免添加空⽩页
if(leftHeight > 0) {
pdf.addPage();
}
}
}
pdf.save('content.pdf');
}
})
}
</script>
</body>
</html>
3.wkhtmltopdf
wkhtmltopdf --disable-smart-shrinking wwwblogs/jiangwz myBlog.pdf
⽣成的PDF⽂件:

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。