当前位置:首页 » 编程语言 » htmltopdfjava

htmltopdfjava

发布时间: 2023-08-12 16:36:22

java将html文件转成pdf

可以通过使用Spire.Doc for Java进行转换。

首先需要安装Spire.Doc for Java。可在 Java 程序中添加 Spire.Doc for Java 文件作为依赖项。JAR 文件可以从此链接下载。 如果您使用 Maven,则可以将以下代码添加到项目的 pom.xml 文件中,从而轻松地在应用程序中导入 JAR 文件。

<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.cn/repository/maven-public/</url>
</repository></repositories><dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.doc</artifactId>
<version>5.2.3</version>
</dependency></dependencies>

具体分为以下两种情况:

  1. HTML String另存为PDF格式

Java代码如下:

import com.spire.doc.*;import java.io.*;public class htmlStringToWord {

public static void main(String[] args) throws Exception {

String inputHtml = "InputHtml.txt";
//新建Document对象
Document document = new Document();
//添加section
Section sec = document.addSection();

String htmlText = readTextFromFile(inputHtml);
//添加段落并写入HTML文本
sec.addParagraph().appendHTML(htmlText);

//文档另存为PDF
document.saveToFile("HTMLstringToPDF.pdf", FileFormat.PDF);
}
public static String readTextFromFile(String fileName) throws IOException{
StringBuffer sb = new StringBuffer();
BufferedReader br = new BufferedReader(new FileReader(fileName));
String content = null;
while ((content = br.readLine()) != null) {
sb.append(content);
}
return sb.toString();
}

}

2.HTML file另存为PDF格式

import com.spire.doc.*;import com.spire.doc.documents.XHTMLValidationType;public class htmlFileToWord {

public static void main(String[] args) throws Exception {
//加载HTML文档
Document document = new Document();
document.loadFromFile("InputHtmlFile.html", FileFormat.Html, XHTMLValidationType.None);

//文档另存为PDF
document.saveToFile("Result.pdf",FileFormat.PDF);
}

}

希望对您有帮助。

② java怎么把HTML界面做成pdf格式打印

public boolean convertHtmlToPdf(String inputFile, String outputFile)
throws Exception {

OutputStream os = new FileOutputStream(outputFile);
ITextRenderer renderer = new ITextRenderer();
String url = new File(inputFile).toURI().toURL().toString();

renderer.setDocument(url);

// 解决中文支持问题
ITextFontResolver fontResolver = renderer.getFontResolver();
fontResolver.addFont("C:/Windows/Fonts/SIMSUN.TTC", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
//解决图片的相对路径问题
renderer.getSharedContext().setBaseURL("file:/D:/");
renderer.layout();
renderer.createPDF(os);

os.flush();
os.close();
return true;
}

上面这段代码是这样的,输入一个HTML地址URL = inputFile,输入一个要输出的地址,就可以在输出的PDF地址中生成这个PDF。

数据库及pdf文件输出

【C++库】

PDF类库 PoDoFo
http://podofo.sourceforge.net/
PoDoFo 是一个用来操作 PDF 文件格式的 C++ 类库。它还包含一些小工具用来解析、修改和创建 PDF 文档。

Xpdf
http://www.foolabs.com/xpdf/download.html
Xpdf是一个开放源代码的PDF档案浏览器,Xpdf 可解码LZW压缩格式并阅读加密的PDF文件。

PDF生成工具 Poppler
http://poppler.freedesktop.org/
Poppler 是一个用来生成 PDF 的C++类库,从xpdf 继承而来。它使用了很多先进的类库例如 freetype 和 cairois 来达到更好的输出效果,同时也提供了一组命令行工具包。

JagPDF
http://www.jagpdf.com/
JagPDF 提供给 C/C++ 和 python 编程语言用来生成 PDF 文档的库。

libHaru
http://libharu.org/wiki/Downloads
开源的PDF库

CLibPDF
http://hpux.connect.org.uk/hppd/hpux/Shells/ClibPDF-2.02/
ClibPDF是C函数库,可以直接生成PDF文件, 不需要Adobe Acrobat等工具支持.

------------------------------------------------------------------------

【JAVA库】
PDF操作类库 iText
http://www.lowagie.com/iText/
iText是一个能够快速产生PDF文件的java类库。iText的java类对于那些要产生包含文本,表格,图形的只读文档是很有用的。它的类库尤其与java Servlet有很好的给合。使用iText与PDF能够使你正确的控制Servlet的输出。

PDFBox
http://www.pdfbox.org/
非常强悍的PDF生成和解析Java类库

jpedal
http://www.jpedal.org/
jpedal是开源纯Java的PDF文档解析库,可以用来读取PDF文档中的文字、图形。

JasperReports
http://jasperforge.org/plugins/project/project_home.php?group_id=102
JasperReports是一个基于Java的开源报表工具,它可以在Java环境下像其它IDE报表工具一样来制作报表。JasperReports 支持PDF、HTML、XLS、CSV和XML文件输出格式。JasperReports是当前Java开发者最常用的报表工具。

Fourfive
http://sourceforge.net/projects/fourfive
Fourfive是一个领先的开源Web报表解决方案,使用XML作为它的配置文件。支持集群、负载平衡、动态发布、PDF, Excel, LDAP,图表、过滤器、排序、布局定制、门户、JasperReports、Velocity模板、兼容Internet Explorer, Netscape, Mozilla, Opera。

FOP
http://xmlgraphics.apache.org/fop/
FOP是由James Tauber发起的一个开源项目,原先的版本是利用xsl-fo将xml文件转换成pdf文件。但最新的版本它可以将xml文件转换成pdf,mif,pcl,txt等多种格式以及直接输出到打印机,并且支持使用SVG描述图形。

JFreeReport
http://sourceforge.net/projects/jfreereport/
JFreeReport是一个用来生成报表的Java类库。它为Java应用程序提供一个灵活的打印功能并支持输出到打印机和PDF, Excel, HTML和XHTML, PlainText, XML和CSV文件中。

YaHP
http://www.allcolor.org/YaHPConverter/
YaHP是一个能够把html文档转换成pdf文档的Java开源包。

PDFjet
http://pdfjet.com/os/edition.html
PDFjet是一个用于动态生成PDF文档的Java类库。支持绘制点、线、方框、圆、贝塞尔曲线(Bezier Curves) 、多边形、星形、复杂路径和形状。支持unicode,文本间距调整,嵌入超链接等。它同时有Java和.NET两个版本。

vPDF
http://sourceforge.net/projects/vpdf/
一个将RTF文档转成PDF文档的工具

【.NET组件】
--------------------------------------------------

iTextSharp
http://itextsharp.sourceforge.net/
iTextSharp 是用来生成 PDF 文档的 C# 组件

PDFsharp
http://www.pdfsharp.com/
PDFsharp is a C# library that easily creates PDF documents on the fly. The same GDI+ like drawing routines can be used to create PDF documents, draw on the screen, or send output to any printer. PDFsharp can also modify, merge, and split existing PDF files or incorporate pages from existing PDF files into new PDF documents.

Report.NET
http://report.sourceforge.net/
Report.NET 是一个功能强大且易用的用来生成 PDF 文档的 C# 组件
---------------------------------------------------------------------

【PHP】

Php Pdf Factory
http://sourceforge.net/projects/pdf-factory/
一个PHP的PDF操作库。

TCPDF
http://www.tecnick.com/public/code/cp_dpage.php?aiocp_dp=tcpdf
TCPDF是一个用于快速生成PDF文件的PHP5函数包。TCPDF基于FPDF进行扩展和改进。支持UTF-8,Unicode,HTML和XHTML。

HTML2PDF
http://html2fpdf.sourceforge.net/
HTML2PDF能够把一个HTML文本转换成一个打印机友好的PDF文件。这个PHP脚本构建在FPDFPHP脚本之上。

cPdfWriter
http://www.palos.ro/index.php?page=opensource_active
cPdfWriter是一个能够输出PDF文档的PHP5 class。基于TCPDF,FPDF和其它相关脚本。

FPDF
http://www.fpdf.org/
FPDF这个PHP Class允许你采用纯PHP(更确切地说就是不需要使用PDFlib)来生成PDF文件。它所具有的特点包括:可选择的unit大小,页面格式和页边 距;页眉和页脚管理;自动分页;自动换行与文本自动对齐;支持JPEG与PNG图片格式;支持着色和文件超链接;支持TrueType,Type1与 encoding;支持页面压缩。...

------------------------------------------------------------------------

【Python和Ruby】
Prawn
http://prawn.majesticseacreature.com/
Prawn: 用Ruby生成PDF更简捷

ReportLab
http://www.reportlab.org/
Reportlab是用python开发的生成pdf的工具包,它是一个开源软件。

PDF生成工具 pyPdf
PyPDF这是一个用于构建PDF的纯Python工具包

④ 如何用纯java代码实现word转pdf

几种方案:
方法一:用apache pio 读取doc文件,然后转成html文件用Jsoup格式化html文件,最后用itext将html文件转成pdf。

方法2:使用jdoctopdf来实现,这是一个封装好的包,可以把doc转换成pdf,html,xml等格式,调用很方便
地址:
需要注意中文字体的写入问题。

方法3:使用jodconverter来调用openOffice的服务来转换,openOffice有个各个平台的版本,所以这种方法跟方法1一样都是跨平台的。
jodconverter的下载地址:
首先要安装openOffice,下载地址:
安装完后要启动openOffice的服务,具体启动方法请自行google

方法4:效果最好的一种方法,但是需要window环境,而且速度是最慢的需要安装msofficeWord以及SaveAsPDFandXPS.exe(word的一个插件,用来把word转化为pdf)
Office版本是2007,因为SaveAsPDFandXPS是微软为office2007及以上版本开发的插件
SaveAsPDFandXPS下载地址:
jacob 包下载地址:

⑤ java把html转成pdf文件

renderer.createPDF( os );捕捉下异常,看是不是跳走廊,在close之前调用os.flush()试试。

String docPath = session.getAttribute("docpath").toString();//获取文件HTML文件路径
String inputFile = docPath+"html"; //定义输入文件全名
String url = new File(inputFile).toURI().toURL().toString();
String outputFile =docPath + "pdf"; //定义输出文件全名
OutputStream os = new FileOutputStream(outputFile);
ITextRenderer renderer = new ITextRenderer(); 实例化一个ITextRenderer
renderer.setDocument(url);
ITextFontResolver fontResolver = renderer.getFontResolver();
ontResolver.addFont("C:/Windows/fonts/simsun.ttc",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED); //设置字体
// 解决图片的相对路径问题
renderer.getSharedContext().setBaseURL("file:/" + application.getRealPath("UserFiles/Image") + "/");
renderer.layout();
renderer.createPDF(os);
os.close();

⑥ java中html字符串如何完美转换成pdf文件

1、首先导入itext的jar包,
然后直接上代码
private static void versionsone(String htmlCode, String pdfPath){
Document document = new Document();
try{
StyleSheet st = new StyleSheet();
st.loadTagStyle("body", "leading", "16,0");
PdfWriter.getInstance(document, new FileOutputStream(pdfPath));
document.open();
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
Font FontChinese = new Font(bfChinese, 12, Font.NORMAL);
ArrayList<ArrayList> p = HTMLWorker.parseToList(dome_2(htmlCode), st);
for(int k=0;k<p.size();k++){
for(int m=0;m<p.get(k).size();m++){
Paragraph pCode = new Paragraph(p.get(k).get(m).toString(),FontChinese);
document.add(pCode);
}
}
}catch(Exception e){
e.printStackTrace();
}finally{
document.close();
}
}

private static Reader dome_2(String htmlCode){
if(htmlCode != null && !htmlCode.trim().equals("")){
try{
InputStream tInputStringStream = new ByteArrayInputStream(htmlCode.getBytes());
InputStreamReader isr = new InputStreamReader(tInputStringStream,"utf-8");
BufferedReader reader = new BufferedReader(isr);
return reader;
}catch(Exception e){
e.printStackTrace();
}

}
return null;
}
其实此处和别人的最大的不一样的是,
ArrayList<ArrayList> p = HTMLWorker.parseToList(dome_2(htmlCode), st);

其实刚刚开始我在网上找来的代码中是这样写的“ArrayList p = HTMLWorker.parseToList(dome_2(htmlCode), st);”
但后来我通过debug发现,ArrayList 里面装的还是一个集合,然后集合中放得才是真正不含html标签的字符串。对于普通得文章,一般html标签一般都是<p></p>
占大多数。所以我直接用了两层for循环直接从里面取得我们想要的字符串。然后直接“Paragraph pCode = new Paragraph(p.get(k).get(m).toString(),FontChinese);”document.add(pCode);这样就能解决中文问题了

⑦ java 有关word,excel,pdf转换成html 有几种方式

java将Word/Excel/PDF文件转换成HTML整理

项目开发过程中,需求涉及到了各种文档转换为HTML或者网页易显示格式,现在将实现方式整理如下:
一、使用Jacob转换Word,Excel为HTML

“JACOB一个Java-COM中间件.通过这个组件你可以在Java应用程序中调用COM组件和Win32 libraries。”

首先下载Jacob包,JDK1.5以上需要使用Jacob1.9版本(JDK1.6尚未测试),与先前的Jacob1.7差别不大

1、将压缩包解压后,Jacob.jar添加到Libraries中;

2、将Jacob.dll放至“WINDOWS\SYSTEM32”下面。

需要注意的是:
【使用IDE启动Web服务器时,系统读取不到Jacob.dll,例如用MyEclipse启动Tomcat,就需要将dll文件到MyEclipse安装目录的“jre\bin”下面。
一般系统没有加载到Jacob.dll文件时,报错信息为:“java.lang.UnsatisfiedLinkError: no jacob in java.library.path”】

新建类:
1public class JacobUtil
2{
3 public static final int WORD_HTML = 8;
4
5 public static final int WORD_TXT = 7;
6
7 public static final int EXCEL_HTML = 44;
8
9 /** *//**
10 * WORD转HTML
11 * @param docfile WORD文件全路径
12 * @param htmlfile 转换后HTML存放路径
13 */
14 public static void wordToHtml(String docfile, String htmlfile)
15 {
16 ActiveXComponent app = new ActiveXComponent("Word.Application"); // 启动word
17 try
18 {
19 app.setProperty("Visible", new Variant(false));
20 Dispatch docs = app.getProperty("Documents").toDispatch();
21 Dispatch doc = Dispatch.invoke(
22 docs,
23 "Open",
24 Dispatch.Method,
25 new Object[] { docfile, new Variant(false),
26 new Variant(true) }, new int[1]).toDispatch();
27 Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] {
28 htmlfile, new Variant(WORD_HTML) }, new int[1]);
29 Variant f = new Variant(false);
30 Dispatch.call(doc, "Close", f);
31 }
32 catch (Exception e)
33 {
34 e.printStackTrace();
35 }
36 finally
37 {
38 app.invoke("Quit", new Variant[] {});
39 }
40 }
41
42 /** *//**
43 * EXCEL转HTML
44 * @param xlsfile EXCEL文件全路径
45 * @param htmlfile 转换后HTML存放路径
46 */
47 public static void excelToHtml(String xlsfile, String htmlfile)
48 {
49 ActiveXComponent app = new ActiveXComponent("Excel.Application"); // 启动word
50 try
51 {
52 app.setProperty("Visible", new Variant(false));
53 Dispatch excels = app.getProperty("Workbooks").toDispatch();
54 Dispatch excel = Dispatch.invoke(
55 excels,
56 "Open",
57 Dispatch.Method,
58 new Object[] { xlsfile, new Variant(false),
59 new Variant(true) }, new int[1]).toDispatch();
60 Dispatch.invoke(excel, "SaveAs", Dispatch.Method, new Object[] {
61 htmlfile, new Variant(EXCEL_HTML) }, new int[1]);
62 Variant f = new Variant(false);
63 Dispatch.call(excel, "Close", f);
64 }
65 catch (Exception e)
66 {
67 e.printStackTrace();
68 }
69 finally
70 {
71 app.invoke("Quit", new Variant[] {});
72 }
73 }
74
75}
76
当时我在找转换控件时,发现网易也转载了一偏关于Jacob使用帮助,但其中出现了比较严重的错误:String htmlfile = "C:\\AA";
只指定到了文件夹一级,正确写法是String htmlfile = "C:\\AA\\xxx.html";

到此WORD/EXCEL转换HTML就已经差不多了,相信大家应该很清楚了:)

二、使用XPDF将PDF转换为HTML

1、下载xpdf最新版本,地址:http://www.foolabs.com/xpdf/download.html
我下载的是xpdf-3.02pl2-win32.zip

2、下载中文支持包
我下载的是xpdf-chinese-simplified.tar.gz

3、下载pdftohtml支持包
地址:http://sourceforge.net/projects/pdftohtml/
我下载的是:pdftohtml-0.39-win32.tar.gz

4、解压调试
1) 先将xpdf-3.02pl2-win32.zip解压,解压后的内容可根据需要进行删减,如果只需要转换为txt格式,其他的exe文件可以删除,只保留pdftotext.exe,以此类推;
2) 然后将xpdf-chinese-simplified.tar.gz解压到刚才xpdf-3.02pl2-win32.zip的解压目录;
3) 将pdftohtml-0.39-win32.tar.gz解压,pdftohtml.exe解压到xpdf-3.02pl2-win32.zip的解压目录;
4) 目录结构:
+---[X:\xpdf]
|-------各种转换用到的exe文件
|
|-------xpdfrc
|
+------[X:\xpdf\xpdf-chinese-simplified]
|
|
+-------很多转换时需要用到的字符文件

xpdfrc:此文件是用来声明转换字符集对应路径的文件

5) 修改xpdfrc文件(文件原名为sample-xpdfrc)
修改文件内容为:
Txt代码

#----- begin Chinese Simplified support package
cidToUnicode Adobe-GB1 xpdf-chinese-simplified\Adobe-GB1.cidToUnicode
unicodeMap ISO-2022-CN xpdf-chinese-simplified\ISO-2022-CN.unicodeMap
unicodeMap EUC-CN xpdf-chinese-simplified\EUC-CN.unicodeMap
unicodeMap GBK xpdf-chinese-simplified\GBK.unicodeMap
cMapDir Adobe-GB1 xpdf-chinese-simplified\CMap
toUnicodeDir xpdf-chinese-simplified\CMap
fontDir C:\WINDOWS\Fonts
displayCIDFontTT Adobe-GB1 C:\WINDOWS\Fonts\simhei.ttf
#----- end Chinese Simplified support package

6) 创建bat文件pdftohtml.bat(放置的路径不能包含空格)
内容为:
Txt代码

@echo off
set folderPath=%1
set filePath=%2
cd /d %folderPath%
pdftohtml -enc GBK %filePath%
exit
7) 创建类

JAVA代码

public class ConvertPdf
{
private static String INPUT_PATH;
private static String PROJECT_PATH;

public static void convertToHtml(String file, String project)
{
INPUT_PATH = file;
PROJECT_PATH = project;
if(checkContentType()==0)
{
toHtml();
}
}

private static int checkContentType()
{
String type = INPUT_PATH.substring(INPUT_PATH.lastIndexOf(".") + 1, INPUT_PATH.length())
.toLowerCase();
if (type.equals("pdf"))
return 0;
else
return 9;
}

private static void toHtml()
{
if(new File(INPUT_PATH).isFile())
{
try
{
String cmd = "cmd /c start X:\\pdftohtml.bat \"" + PROJECT_PATH + "\" \"" + INPUT_PATH + "\"";
Runtime.getRuntime().exec(cmd);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}

}

热点内容
编译器的制作环境 发布:2025-02-06 05:54:34 浏览:828
学车网源码 发布:2025-02-06 05:47:40 浏览:385
搭建局域网影院服务器 发布:2025-02-06 05:47:38 浏览:759
广东一区cf刷经验房密码都是什么 发布:2025-02-06 05:46:20 浏览:633
加密工具源码 发布:2025-02-06 05:44:52 浏览:13
笔记本可用存储多大 发布:2025-02-06 05:44:48 浏览:157
ftp登录后没有反应 发布:2025-02-06 05:29:41 浏览:175
linux建目录命令 发布:2025-02-06 05:29:06 浏览:724
安卓所有照片在哪里 发布:2025-02-06 05:16:32 浏览:972
l2缓存作用 发布:2025-02-06 05:15:02 浏览:291