整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:

java将html转为pdf


html转为pdf的组件有很多,但是还没有哪一款能达到这个效果,其只要原因是wkhtmltopdf使用webkit网页渲染引擎开发的用来将 html转成 pdf的工具,可以跟多种脚本语言进行集成来转换文档。但是就使用简便性来说还是itext等组件占据优势,如果你要转换格式有比较高的要求,那么wkhtmltopdf绝对是不二之选!

下载路径

官网地址 wkhtmltopdf.org/

github地址 github.com/wkhtmltopdf…

使用方法

  1. windows直接使用:只要在windows命令行中输入c:\wkhtmltopdf.exe my.oschina.net/papio/blog/… c:\blog.pdf 就可以把这篇文章转成pdf,并保存到C盘根目录。
  2. java调用:java中调用wkhtmltopdf的命令Runtime.getRuntime().exec("c:\wkhtmltopdf.exe my.oschina.net/papio/blog/… c:\blog.pdf")就可以实现转换。

java调用demo

public class HtmlToPdfInterceptor extends Thread { private InputStream is; public HtmlToPdfInterceptor(InputStream is){ this.is = is; } public void run(){ try{ InputStreamReader isr = new InputStreamReader(is, "utf-8"); BufferedReader br = new BufferedReader(isr); String line = null; while ((line = br.readLine()) != null) { System.out.println(line.toString()); //输出内容 } }catch (IOException e){ e.printStackTrace(); } }}public class HtmlToPdf { //wkhtmltopdf在系统中的路径 private static final String toPdfTool = "D:\wkhtmltopdf\bin\wkhtmltopdf.exe"; /** * html转pdf * @param srcPath html路径,可以是硬盘上的路径,也可以是网络路径 * @param destPath pdf保存路径 * @return 转换成功返回true */ public static boolean convert(String srcPath, String destPath){ File file = new File(destPath); File parent = file.getParentFile(); //如果pdf保存路径不存在,则创建路径 if(!parent.exists()){ parent.mkdirs(); } StringBuilder cmd = new StringBuilder(); cmd.append(toPdfTool); cmd.append(" "); cmd.append(" --header-line");//页眉下面的线 cmd.append(" --header-center 这里是页眉这里是页眉这里是页眉这里是页眉 ");//页眉中间内容 //cmd.append(" --margin-top 30mm ");//设置页面上边距 (default 10mm) cmd.append(" --header-spacing 10 ");//(设置页眉和内容的距离,默认0) cmd.append(srcPath); cmd.append(" "); cmd.append(destPath); boolean result = true; try{ Process proc = Runtime.getRuntime().exec(cmd.toString()); HtmlToPdfInterceptor error = new HtmlToPdfInterceptor(proc.getErrorStream()); HtmlToPdfInterceptor output = new HtmlToPdfInterceptor(proc.getInputStream()); error.start(); output.start(); proc.waitFor(); }catch(Exception e){ result = false; e.printStackTrace(); } return result; } public static void main(String[] args) { HtmlToPdf.convert("https://my.oschina.net/papio/blog/835645", "d:/wkhtmltopdf.pdf"); }}复制代码

wkhtmltopdf 参数详解

wkhtmltopdf [OPTIONS]... <input file> [More input files] <output file>常规选项 --allow <path> 允许加载从指定的文件夹中的文件或文件(可重复) --book* 设置一会打印一本书的时候,通常设置的选项 --collate 打印多份副本时整理 --cookie <name> <value> 设置一个额外的cookie(可重复) --cookie-jar <path> 读取和写入的Cookie,并在提供的cookie jar文件 --copies <number> 复印打印成pdf文件数(默认为1) --cover* <url> 使用HTML文件作为封面。它会带页眉和页脚的TOC之前插入 --custom-header <name> <value> 设置一个附加的HTTP头(可重复) --debug-javascript 显示的javascript调试输出 --default-header* 添加一个缺省的头部,与页面的左边的名称,页面数到右边,例如: --header-left '[webpage]' --header-right '[page]/[toPage]' --header-line --disable-external-links* 禁止生成链接到远程网页 --disable-internal-links* 禁止使用本地链接 --disable-javascript 禁止让网页执行JavaScript --disable-pdf-compression* 禁止在PDF对象使用无损压缩 --disable-smart-shrinking* 禁止使用WebKit的智能战略收缩,使像素/ DPI比没有不变 --disallow-local-file-access 禁止允许转换的本地文件读取其他本地文件,除非explecitily允许用 --allow --dpi <dpi> 显式更改DPI(这对基于X11的系统没有任何影响) --enable-plugins 启用已安装的插件(如Flash --encoding <encoding> 设置默认的文字编码 --extended-help 显示更广泛的帮助,详细介绍了不常见的命令开关 --forms* 打开HTML表单字段转换为PDF表单域 --grayscale PDF格式将在灰阶产生 --help Display help --htmldoc 输出程序HTML帮助 --ignore-load-errors 忽略claimes加载过程中已经遇到了一个错误页面 --lowquality 产生低品质的PDF/ PS。有用缩小结果文档的空间 --manpage 输出程序手册页 --margin-bottom <unitreal> 设置页面下边距 (default 10mm) --margin-left <unitreal> 将左边页边距 (default 10mm) --margin-right <unitreal> 设置页面右边距 (default 10mm) --margin-top <unitreal> 设置页面上边距 (default 10mm) --minimum-font-size <int> 最小字体大小 (default 5) --no-background 不打印背景 --orientation <orientation> 设置方向为横向或纵向 --page-height <unitreal> 页面高度 (default unit millimeter) --page-offset* <offset> 设置起始页码 (default 1) --page-size <size> 设置纸张大小: A4, Letter, etc. --page-width <unitreal> 页面宽度 (default unit millimeter) --password <password> HTTP验证密码 --post <name> <value> Add an additional post field (repeatable) --post-file <name> <path> Post an aditional file (repeatable) --print-media-type* 使用的打印介质类型,而不是屏幕 --proxy <proxy> 使用代理 --quiet Be less verbose --read-args-from-stdin 读取标准输入的命令行参数 --readme 输出程序自述 --redirect-delay <msec> 等待几毫秒为JS-重定向(default 200) --replace* <name> <value> 替换名称,值的页眉和页脚(可重复) --stop-slow-scripts 停止运行缓慢的JavaScripts --title <text> 生成的PDF文件的标题(第一个文档的标题使用,如果没有指定) --toc* 插入的内容的表中的文件的开头 --use-xserver* 使用X服务器(一些插件和其他的东西没有X11可能无法正常工作) --user-style-sheet <url> 指定用户的样式表,加载在每一页中 --username <username> HTTP认证的用户名 --version 输出版本信息退出 --zoom <float> 使用这个缩放因子 (default 1) 页眉和页脚选项--header-center* <text> (设置在中心位置的页眉内容) --header-font-name* <name> (default Arial) (设置页眉的字体名称)--header-font-size* <size> (设置页眉的字体大小)--header-html* <url> (添加一个HTML页眉,后面是网址)--header-left* <text> (左对齐的页眉文本)--header-line* (显示一条线在页眉下)--header-right* <text> (右对齐页眉文本)--header-spacing* <real> (设置页眉和内容的距离,默认0)--footer-center* <text> (设置在中心位置的页脚内容) --footer-font-name* <name> (设置页脚的字体名称) --footer-font-size* <size> (设置页脚的字体大小default 11)--footer-html* <url> (添加一个HTML页脚,后面是网址)--footer-left* <text> (左对齐的页脚文本)--footer-line* 显示一条线在页脚内容上)--footer-right* <text> (右对齐页脚文本)--footer-spacing* <real> (设置页脚和内容的距离)./wkhtmltopdf --footer-right '[page]/[topage]' http://www.baidu.com baidu.pdf./wkhtmltopdf --header-center '报表' --header-line --margin-top 2cm --header-line http://192.168.212.139/oma/ oma.pdf表内容选项中 --toc-depth* <level> Set the depth of the toc (default 3) --toc-disable-back-links* Do not link from section header to toc --toc-disable-links* Do not link from toc to sections --toc-font-name* <name> Set the font used for the toc (default Arial) --toc-header-font-name* <name> The font of the toc header (if unset use --toc-font-name) --toc-header-font-size* <size> The font size of the toc header (default 15) --toc-header-text* <text> The header text of the toc (default Table Of Contents) --toc-l1-font-size* <size> Set the font size on level 1 of the toc (default 12) --toc-l1-indentation* <num> Set indentation on level 1 of the toc (default 0) --toc-l2-font-size* <size> Set the font size on level 2 of the toc (default 10) --toc-l2-indentation* <num> Set indentation on level 2 of the toc (default 20) --toc-l3-font-size* <size> Set the font size on level 3 of the toc (default 8) --toc-l3-indentation* <num> Set indentation on level 3 of the toc (default 40) --toc-l4-font-size* <size> Set the font size on level 4 of the toc (default 6) --toc-l4-indentation* <num> Set indentation on level 4 of the toc (default 60) --toc-l5-font-size* <size> Set the font size on level 5 of the toc (default 4) --toc-l5-indentation* <num> Set indentation on level 5 of the toc (default 80) --toc-l6-font-size* <size> Set the font size on level 6 of the toc (default 2) --toc-l6-indentation* <num> Set indentation on level 6 of the toc (default 100) --toc-l7-font-size* <size> Set the font size on level 7 of the toc (default 0) --toc-l7-indentation* <num> Set indentation on level 7 of the toc (default 120) --toc-no-dots* Do not use dots, in the toc轮廓选项 --dump-outline <file> 转储目录到一个文件 --outline 显示目录(文章中h1,h2来定) --outline-depth <level> 设置目录的深度(默认为4)页脚和页眉 * [page] 由当前正在打印的页的数目代替 * [frompage] 由要打印的第一页的数量取代 * [topage] 由最后一页要打印的数量取代 * [webpage] 通过正在打印的页面的URL替换 * [section] 由当前节的名称替换 * [subsection] 由当前小节的名称替换 * [date] 由当前日期系统的本地格式取代 * [time] 由当前时间,系统的本地格式取代
作者:曹元
链接:https://juejin.im/post/6856547881873047559
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

TML常用标签有:a标签、table标签、img标签、form标签和input标签。

a标签

作用

  1. 跳转到外部网页
  2. 跳转到内部锚点
  3. 跳转到邮箱或电话等

属性

(一)href

href是hyper reference的缩写,超链接的意思。

用于指定链接目标的ur地址,(必须属性)当为标签应用href属性时,它就具有了超链接的功能;
href=“#”表示这是一个空链接;
如果href里面地址是—个文件或者压缩包,会下载这个文件。

<a href="https://google.com">超链接到google网站的主页</a>
 <a href="https://google.com">超链接到google的主页</a>
 <a href="//google.com">超链接到google的主页</a>

展现形式:

点击此链接,即可到达google的主页

a标签href的取值:

1、上述代码中的网址的取值(推荐使用第三行的代码)

<a href="//google.com">超链接到google的主页</a>

由于此方式能够自动补齐相关的网络地址,前面两种写错就会报错,所以推荐使用。

2、路径

  • /a/b/c 或者是a/b/c

当前路径下的a里面的b,b里面的c

  • index.html 以及./index.html

在当前目录下寻找index.html文件

3、伪协议

  • javascript:代码;(冒号与分号一定要写)
<a href="javascript:;">点击后无任何点击或刷新等动作的反应</a>
  • 锚点链接
<a href="#要跳转的元素的id"></a>

点击链接的时候,会跳转到指定元素所在的位置。

  • mailto:邮箱
<a href="mailto:abcdefg@163.com ">发邮件给我</a>
  • tel:手机号
<a href="tel:12345678901">打电话给我</a>

(二)targe

用于指定链接页面的打开方式

a的target取值

1、内置名字

_blank 在空白页打开

_self 在当前页面打开

_parent 在父级窗口打开

_top 在最顶级的窗口打开

<a href="//google.com" target="_blank">超链接到google网站的主页在空白页打开</a>

2、程序员的命名

window:name(在xxx页面打开)

iframe的name(iframe现在已经很少使用了,是指内嵌窗口)


(三)download

下载页面,但目前很少用,有的浏览器不支持,尤其是手机浏览器可能不支持。

table标签

1、table标签的语法:

thead:表头

tbody:表的内容,用于定义

tfoot:表的脚部

tr:table row,表格里的行

th:表格的表头部分,其中的文本内容字体加粗居中显示

td:table data,表格数据,用于定义表格中的单元格

<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
  </head>
  <body>
    <table>
      <thead>
        <tr>
          <th></th>
          <th>小红</th>
          <th>小黄</th>
          <th>小蓝</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <th>数学</th>
          <td>90</td>
          <td>60</td>
          <td>80</td>
        </tr>
        <tr>
          <th>语文</th>
          <td>88</td>
          <td>95</td>
          <td>97</td>
        </tr>
        <tr>
          <th>英语</th>
          <td>88</td>
          <td>95</td>
          <td>97</td>
        </tr>
      </tbody>
      <tfoot>
        <tr>
          <th>总分</th>
          <td>266</td>
          <td>250</td>
          <td>274</td>
        </tr>
      </tfoot>
    </table>
  </body>
</html>



第一行的th标签为空

2、table的样式

table-layout:auto;自动计算每一行的宽高

table-layout:fixed;通过列表的宽度来决定平均宽度

border-collapse:collapse; 合并边框(默认边框与边框之间不合并)

border-spacing:0;边框为0.(边框与边框之间的距离)。

img标签(图片)

作用:发出get请求,展示一张图片。

<img src="1.JPG" alt="头像" width="400" />

当前路径下的1.jpg,确定宽度为400,只写宽度高度会自适应

属性

alt:alternate的缩写,替换的意思。替换文本,图像不能显示的文字。

路径错误显示alt内容

title:提示文本。鼠标放到图像上,显示的文字。

响应

max-width:100% 所有的图片在手机上都自适应宽度,宽度最大为100%。

事件

onload/onerror 监听图片是否加载成功,加载成功时用onload,不成功是用onerror事件。确保在onerror事件能够补救。

<body>
 <img id="xxx" src="dog.jpg" alt="一只小狗">
<script>
xxx.onload = function () {
console.log("图片加载成功");
 };
xxx.onerror = function () {
console.log("图片加载失败");
xxx.src = "/404.jpg";
 };
</script>
</body>

监听成功时,打印出成功

监听失败时,先打印出监听失败并且开始执行加载失败是的挽救图片。404.jpg文件执行

感想:

  • a标签的默认样式可以设置清除,href属性可以有好多种取值,a标签的意义也不仅仅是跳转到一个网址,还可以发邮件打电话。
  • 给img标签设置宽度和高度时,不能让图片变形
  • table标签必须按照thead,tbody,tfoot的结构去写,先划分好结构,再往里填充内容,即使tfoot写在前面,也会显示在页面的尾部

本文为作者本人的原创文章,著作权归作者本人和饥人谷所有,转载务必注明来源。

spose.Words无需Microsoft Word也可在任何平台上满足Word文档的一切操作需求。本文将与大家分享如何将word和图像转换为PDF

将HTML转换为PDF

要将HTML转换为PDF,只需调用Document.Save方法并指定扩展名为“.PDF”即可。如果要从外部源加载图像和CSS等,可以使用IResourceSavingCallback。下面的代码示例演示将HTML转换为PDF并从外部源加载图像。

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
public class ImageLoadingWithCredentialsHandler : IResourceLoadingCallback
{
 public ImageLoadingWithCredentialsHandler()
 {
 mWebClient = new WebClient();
 }
 public ResourceLoadingAction ResourceLoading(ResourceLoadingArgs args)
 {
 if (args.ResourceType == ResourceType.Image)
 {
 Uri uri = new Uri(args.Uri);
 if (uri.Host == "www.aspose.com")
 mWebClient.Credentials = new NetworkCredential("User1", "akjdlsfkjs");
 else
 mWebClient.Credentials = new NetworkCredential("SomeOtherUserID", "wiurlnlvs");
 // Download the bytes from the location referenced by the URI.
 byte[] imageBytes = mWebClient.DownloadData(args.Uri);
 args.SetData(imageBytes);
 return ResourceLoadingAction.UserProvided;
 }
 else
 {
 return ResourceLoadingAction.Default;
 }
 }
 private WebClient mWebClient;
}

在Base64编码中将字体导出为HTML

使用Aspose.Words我们可以检查字体资源是否应该以base 64编码嵌入到HTML中。默认情况下,该值为false,字体将写入单独的文件。如果此选项设置为true,则字体将嵌入到Base64编码的文档CSS中。 该属性仅影响HTML格式,不会影响EPUB和MHTML。这是HtmlSaveOptions.ExportFontResources选项的扩展,ExportFontsAsBase64仅在此属性设置为true时才有效。下面的示例演示如何使用Base64编码将字体导出为HTML。

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
string fileName = "Document.doc";
Document doc = new Document(dataDir + fileName);
HtmlSaveOptions saveOptions = new HtmlSaveOptions();
saveOptions.ExportFontResources = true;
saveOptions.ExportFontsAsBase64 = true; 
dataDir = dataDir + "ExportFontsAsBase64_out.html";
doc.Save(dataDir, saveOptions);

使用HtmlSaveOptions属性

使用Aspose.Words,我们可以指定一个文件夹,在将文档导出为HTML时,可以保存图像,字体和外部CSS等所有资源。默认值为空字符串。ResourceFolder是指定应写入所有资源的文件夹的最简单方法。我们可以使用FontsFolder等单独的属性将字体保存到指定的文件夹,使用ImagesFolder将图像保存到指定的文件夹。

使用ResourceFolderAlias属性,我们还可以指定用于构造写入HTML文档的所有资源的URI的文件夹的名称,这是指定应如何构造所有资源文件的URI的最简单方法。可以通过ImagesFolderAlias和FontsFolderAliasproperties分别为图像和字体指定相同的信息。 但是,CSS没有单独的属性。 FontsFolder,FontsFolderAlias,ImagesFolder,ImagesFolderAlias和CssStyleSheetFileName属性的行为不会更改。请注意,CssStyleSheetFileName属性用于指定文件夹名称和文件名。

指定相对路径时,FontsFolder和ImagesFolder相对于代码程序集所在的文件夹,ResourceFolder和CssStyleSheetFileName相对于HTML文档所在的输出文件夹。在下面的示例中,ResourceFolder指定此路径相对于输出文件夹的相对路径,其中保存HTML文档,http://example.com/resources 别名用于构造所有资源的URL。

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
string fileName = "Document.doc";
Document doc = new Document(dataDir + fileName);
HtmlSaveOptions saveOptions = new HtmlSaveOptions();
saveOptions.CssStyleSheetType = CssStyleSheetType.External;
saveOptions.ExportFontResources = true;
saveOptions.ResourceFolder = dataDir + @"\Resources";
saveOptions.ResourceFolderAlias = "http://example.com/resources";
doc.Save(dataDir + "ExportResourcesUsingHtmlSaveOptions.html", saveOptions);

如何将文档转换为MHTML和电子邮件

Aspose.Words可以以MHTML(Web Archive)格式保存任何文档。这使得Aspose.Words和Aspose.Email一起使用可以生成和发送内容丰富的电子邮件。例如,你可以将预定义的DOC,OOXML或RTF文档加载到Aspose.Words中,用数据填充之后另存为MHTML,然后使用Aspose.Email发送电子邮件。 下面的代码示例演示了如何使用Aspose.Email将Aspose.Words中的文档保存为MHTML和电子邮件。

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Load the document into Aspose.Words.
Document doc = new Document(dataDir + "Test File (docx).docx");
// Save into a memory stream in MHTML format.
Stream stream = new MemoryStream();
doc.Save(stream, SaveFormat.Mhtml);
// Rewind the stream to the beginning so Aspose.Email can read it.
stream.Position = 0;
// Create an Aspose.Network MIME email message from the stream.
MailMessage message = MailMessage.Load(stream, new MhtmlLoadOptions());
message.From = "your_from@email.com";
message.To = "your_to@email.com";
message.Subject = "Aspose.Words + Aspose.Email MHTML Test Message";
// Send the message using Aspose.Email
SmtpClient client = new SmtpClient();
client.Host = "your_smtp.com";
client.Send(message);

点击“了解更多”下载产品最新版

↓↓↓