當前位置:首頁 » 編程語言 » 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 06:45:04 瀏覽:528
驚聲尖笑5下載ftp 發布:2025-02-06 06:33:16 瀏覽:528
共享文件夾讓輸入密碼 發布:2025-02-06 06:32:28 瀏覽:970
收銀伺服器響應出錯什麼意思 發布:2025-02-06 06:24:43 瀏覽:607
sql用戶授權 發布:2025-02-06 06:24:42 瀏覽:677
蘋果手機相冊顯示正在上傳 發布:2025-02-06 06:05:43 瀏覽:542
hadoop下載文件夾 發布:2025-02-06 06:05:08 瀏覽:187
鎧最強配置是哪些 發布:2025-02-06 06:04:22 瀏覽:360
編譯器的製作環境 發布:2025-02-06 05:54:34 瀏覽:829
學車網源碼 發布:2025-02-06 05:47:40 瀏覽:386