您的位置:首页 > Web前端 > HTML

JAVA常用API或编程工具001---ITEXT把html转换成pdf的jar包,使用Java将HTML转换为PDF

2017-03-31 18:28 876 查看
iText“XMLWorker”允许开发人员以一种程序员友好的方式将XML文件转换成PDF文件。iText还可以将包含CSS样式的HTML转换为PDF格式的文档。


目标:

实现如何利用iTextJava库将HTML文件转换成PDF文档?


Environment&Tools

Eclipse(oranyotherIDE)
Maven(optional)


Library:

iText5.4.2

Listofjarfiles:.classpath
ListofMavendependencies:pom.xml


(1)HTMLFile

index.html

01
<!DOCTYPE
htmlPUBLIC"-//W3C//DTDHTML4.01Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
02
<
html
>
03
<
head
>
04
<
title
>HTML
toPDF</
title
>
05
<
link
href
=
"style.css"
rel
=
"stylesheet"
type
=
"text/css"
/>
06
</
head
>
07
<
body
>
08
<
h1
>HTML
toPDF</
h1
>
09
<
p
>
10
<
span
class
=
"itext"
>itext</
span
>
5.4.2<
span
class
=
"description"
>
convertingHTMLtoPDF</
span
>
11
</
p
>
12
<
table
>
13
<
tr
>
14
<
th
class
=
"label"
>Title</
th
>
15
<
td
>iText
-JavaHTMLtoPDF</
td
>
16
</
tr
>
17
<
tr
>
18
<
th
>URL</
th
>
19
<
td
>http://hmkcode.com/itext-html-to-pdf-using-java</
td
>
20
</
tr
>
21
</
table
>
22
</
body
>
23
</
html
>
style.css

01
h
1
{
02
color
:
#ccc
;
03
}
04
table
trtd{
05
text-align
:
center
;
06
border
:
1px
solid
gray
;
07
padding
:
4px
;
08
}
09
table
trth{
10
background-color
:
#84C7FD
;
11
color
:
#fff
;
12
width
:
100px
;
13
}
14
.itext{
15
color
:
#84C7FD
;
16
font-weight
:
bold
;
17
}
18
.description{
19
color
:
gray
;
20
}

(2)JavaApp

App.java

01
package
com.hmkcode;
02
03
import
java.io.FileInputStream;
04
import
java.io.FileOutputStream;
05
import
java.io.IOException;
06
import
com.itextpdf.text.Document;
07
import
com.itextpdf.text.DocumentException;
08
import
com.itextpdf.text.pdf.PdfWriter;
09
import
com.itextpdf.tool.xml.XMLWorkerHelper;
10
11
public
class
App
12
{
13
public
static
void
main(
String[]args)
throws
DocumentException,
IOException
14
{
15
//
step1
16
Document
document=
new
Document();
17
//
step2
18
PdfWriter
writer=PdfWriter.getInstance(document,
new
FileOutputStream(
"pdf.pdf"
));
19
//
step3
20
document.open();
21
//
step4
22
XMLWorkerHelper.getInstance().parseXHtml(writer,
document,
23
new
FileInputStream(
"index.html"
));
24
//step
5
25
document.close();
26
27
System.out.println(
"PDF
Created!"
);
28
}
29
}

(3)Output“PDF”



SourceCode@GitHub

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: