如果您对从XML或HTML生成PDF文件和xml转成html感兴趣,那么这篇文章一定是您不可错过的。我们将详细讲解从XML或HTML生成PDF文件的各种细节,并对xml转成html进行深入的分析,此外
如果您对从XML或HTML生成PDF文件和xml转成html感兴趣,那么这篇文章一定是您不可错过的。我们将详细讲解从XML或HTML生成PDF文件的各种细节,并对xml转成html进行深入的分析,此外还有关于C#使用wkhtmltopdf,把HTML生成PDF(包含分页)、C#编写 HTML生成PDF、html生成pdf、java html生成PDF,并打印的实用技巧。
本文目录一览:- 从XML或HTML生成PDF文件(xml转成html)
- C#使用wkhtmltopdf,把HTML生成PDF(包含分页)
- C#编写 HTML生成PDF
- html生成pdf
- java html生成PDF,并打印
从XML或HTML生成PDF文件(xml转成html)
是否有任何API /解决方案可从XML文件数据和定义生成PDF报告。例如,XML定义/数据可以是:
<pdf>
<paragraph font="Arial">Title of report</paragraph>
</pdf>
我觉得将HTML转换为PDF也是一个很好的解决方案。
当前,我们使用iText API编写Java代码。我想外部化代码,以便非技术人员可以编辑和更改。
C#使用wkhtmltopdf,把HTML生成PDF(包含分页)
最近花了2天多的时间终于把HTML生成PDF弄好了。步骤如下:
1、首先是技术选型。看了好多都是收费的就不考虑了。
免费的有:
- jsPDF(前端生成,清晰度不高,生成比较慢)
- iText(严格要求html标签。这个好像也是收费的)
- wkhtmltopdf(简单、配置选项多、生成快、支持跨平台、也支持HTML生成图片)
因此选择wkhtmltopdf。
2、前期准备,首先需要下载wkhtmltopdf.exe(下载地址:https://wkhtmltopdf.org/downloads.html)阅读配置参数(https://wkhtmltopdf.org/usage/wkhtmltopdf.txt)
常用参数:
- -T 0 :设置上下左右margin-top=0(-B 0 -L 0 -R 0 -T 0,上下左右都设置一下)
- -s A4:设置A4纸大小,默认A4
- --disable-smart-shrinking:禁止缩放(不设置这个,生成的pdf会缩放)
- --zoom 1:设置缩放系数,默认为1。如果--disable-smart-shrinking设置了,--zoom就不用设置了。
- --cookie name value:设置cookie,如果下载的url需要登录(用cookie),那么这个参数很重要。
3、设置需要打印的页面(核心是分页)
A4纸大小:210mm×297mm,因此页面的每个div大小也是A4纸大小。
这里的页面设置很重要。另外,设置了分页的页码,示例如下:
<style>
#view {
height: 100%;
margin: auto;
padding: 0;
width: 210mm;
}
/*设置A4打印页面*/
/*备注:由于@是否特殊符号,样式放在css文件中没问题,放在cshtml文件就不行了,需要@@。*/
@preview-item {
size: A4;
margin: 0;
}
@media print {
.preview-item {
margin: 0;
border: initial;
border-radius: initial;
width: initial;
min-height: initial;
box-shadow: initial;
background: initial;
page-break-after: always;
}
}
.preview-item {
width: 100%;
height: 297mm;
position: relative;
}
.page-view {
position: absolute;
width: 100%;
text-align: center;
height: 60px;
line-height: 60px;
bottom: 0;
}
</style>
<div id="view">
<div class="preview-item">
<div class="preview-item-body">这是第一页</div>
<div class="page-view">1/3</div>
</div>
<div class="preview-item">
<div class="preview-item-body">这是第二页</div>
<div class="page-view">2/3</div>
</div>
<div class="preview-item">
<div class="preview-item-body">这是第三页</div>
<div class="page-view">3/3</div>
</div>
</div>
4、C#代码实现(核心是Arguments的设置)
/// <summary>
/// HTML生成PDF
/// </summary>
/// <param name="url">url地址(需要包含HTTP://)</param>
/// <param name="path">PDF存放路径(可以是aaa.pdf,也可以用路径,只能是绝对地址,如:D://aaa.pdf)</param>
public static bool HtmlToPdf(string url, string path)
{
path = HttpContext.Current.Server.MapPath(path);string cookie = "cookieKey cookieValue";//改为为你自己的
string Arguments = "-q -B 0 -L 0 -R 0 -T 0 -s A4 --no-background --disable-smart-shrinking --cookie " + cookie + " " + url + " " + path; //参数可以根据自己的需要进行修改
try
{
if (string.IsNullOrEmpty(url) || string.IsNullOrEmpty(path))
return false;
var p = new Process();
string str = HttpContext.Current.Server.MapPath("/htmlToPDF/wkhtmltopdf.exe");
if (!File.Exists(str))
return false;
p.StartInfo.FileName = str;
p.StartInfo.Arguments = Arguments;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = false;
p.Start();
p.WaitForExit();
System.Threading.Thread.Sleep(1000);
return true;
}
catch (Exception ex)
{
LogHelper.WriteError(ex);
}
return false;
}
方法的调用:
string url = Request.Url.AbsoluteUri.Replace("DownloadPDF", "Detail");//DownloadPDF是下载页面,Detail是上面的HTML页面
string pdfDirectory = "/Data/PDF/";
if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(pdfDirectory)))
{
System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(pdfDirectory));
}
string path = pdfDirectory + Guid.NewGuid() + ".pdf";
HtmlToPdf(url, path);
if (!System.IO.File.Exists(Utils.GetMapPath(path)))//如果生成失败,重试一次
{
HtmlToPdfHelper.HtmlToPdf(url, path);
}
if (!System.IO.File.Exists(Utils.GetMapPath(path)))//如果生成失败,重试一次
{
HtmlToPdfHelper.HtmlToPdf(url, path);
}
5、ok,采坑结束~
C#编写 HTML生成PDF
下面是小编 jb51.cc 通过网络收集整理的代码片段。
小编小编现在分享给大家,也给大家做个参考。
{
bool success = true;
string dwbh = url.Split('?')[1].Split('=')[1];
//CommonBllHelper.createuserDir(dwbh);
url = Request.Url.Host + "/html/" + url;
string guid = DateTime.Now.ToString("yyyyMMddhhmmss");
string pdfName = guid + ".pdf";
//string path = Server.MapPath("~/kehu/" + dwbh + "/pdf/") + pdfName;
string path = "D:\\Temp\\" + pdfName;
try
{
if (string.IsNullOrEmpty(url) || string.IsNullOrEmpty(path))
success = false;
string str = Server.MapPath("~\\tools\\wkhtmltopdf\\bin\\wkhtmltopdf.exe");
Process p = System.Diagnostics.Process.Start(str,url + " " + path);
p.WaitForExit();
if (!System.IO.File.Exists(str))
success = false;
if (System.IO.File.Exists(path))
{
FileStream fs = new FileStream(path,FileMode.Open);
byte[] bytes = new byte[(int)fs.Length];
fs.Read(bytes,bytes.Length);
fs.Close();
if (Request.UserAgent != null)
{
string userAgent = Request.UserAgent.toupper();
if (userAgent.IndexOf("FIREFOX",StringComparison.Ordinal) <= 0)
{
response.addheader("Content-disposition",
"attachment; filename=" + HttpUtility.UrlEncode(pdfName,Encoding.UTF8));
}
else
{
response.addheader("Content-disposition","attachment; filename=" + pdfName);
}
}
Response.ContentEncoding = Encoding.UTF8;
Response.ContentType = "application/octet-stream";
//通知浏览器下载文件而不是打开
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
fs.Close();
System.IO.File.Delete(path);
}
else
{
Response.Write("文件未找到,可能已经被删除");
Response.Flush();
Response.End();
}
}
catch (Exception ex)
{
success = false;
}
var rlt = new { success = success };
return Json(rlt,JsonRequestBehavior.AllowGet);
}
以上是小编(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。
如果觉得小编网站内容还不错,欢迎将小编网站推荐给程序员好友。
html生成pdf
/** * 生成pdf * @param string $html 需要生成的内容 */ function pdf($html=‘<h1>hello word</h1>‘){ vendor(‘Tcpdf.tcpdf‘); $pdf = new \Tcpdf(PDF_PAGE_ORIENTATION,PDF_UNIT,PDF_PAGE_FORMAT,true,‘UTF-8‘,false); // 设置打印模式 $pdf->SetCreator(PDF_CREATOR); $pdf->SetAuthor(‘Nicola Asuni‘); $pdf->SetTitle(‘TCPDF Example 001‘); $pdf->SetSubject(‘TCPDF Tutorial‘); $pdf->SetKeywords(‘TCPDF,PDF,example,test,guide‘); // 是否显示页眉 $pdf->setPrintHeader(false); // 设置页眉显示的内容 $pdf->SetHeaderData(‘logo.png‘,60,‘baijunyao.com‘,‘白俊遥博客‘,array(0,64,255),128)); // 设置页眉字体 $pdf->setHeaderFont(Array(‘dejavusans‘,‘‘,‘12‘)); // 页眉距离顶部的距离 $pdf->SetHeaderMargin(‘5‘); // 是否显示页脚 $pdf->setPrintFooter(true); // 设置页脚显示的内容 $pdf->setFooterData(array(0,0),128)); // 设置页脚的字体 $pdf->setFooterFont(Array(‘dejavusans‘,‘10‘)); // 设置页脚距离底部的距离 $pdf->SetFooterMargin(‘10‘); // 设置默认等宽字体 $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED); // 设置行高 $pdf->setCellHeightRatio(1); // 设置左、上、右的间距 $pdf->SetMargins(‘10‘,‘10‘,‘10‘); // 设置是否自动分页 距离底部多少距离时分页 $pdf->SetAutopageBreak(TRUE,‘15‘); // 设置图像比例因子 $pdf->setimageScale(PDF_IMAGE_SCALE_RATIO); if (@file_exists(dirname(__FILE__).‘/lang/eng.PHP‘)) { require_once(dirname(__FILE__).‘/lang/eng.PHP‘); $pdf->setLanguageArray($l); } $pdf->setFontSubsetting(true); $pdf->AddPage(); // 设置字体 $pdf->SetFont(‘stsongstdlight‘,14,true); $pdf->writeHTMLCell(0,$html,1,true); $pdf->Output(‘example_001.pdf‘,‘I‘); }
java html生成PDF,并打印
import java.io.File;
import java.io.FileOutputStream;
import org.zefer.pd4ml.PD4Constants;
import org.zefer.pd4ml.PD4ML;
import org.zefer.pd4ml.PD4PageMark;
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.DocAttributeSet;
import javax.print.attribute.HashDocAttributeSet;
import javax.print.attribute.HashPrintRequestAttributeSet;
public void createPDF(String printHtml, File pdffile) throws InvalidParameterException, IOException{
StringBuffer html = new StringBuffer();
html.append("<style>")
.append(" .pageBreak{page-break-after: always; }")
.append("</style>");
html.append(printHtml);
html.append("<pd4ml:page.break>");
StringReader strReader = new StringReader(getHtml(html).toString());
FileOutputStream fos = new FileOutputStream(pdffile);
PD4ML pd4ml = new PD4ML();
pd4ml.setPageInsets(new Insets(5, 5, 5, 5));
pd4ml.setHtmlWidth(700);
pd4ml.setPageSize(PD4Constants.A4);
pd4ml.useTTF("file:"+System.getProperty("ofbiz.home")+"/hot-deploy/heluoexam/webapp/exam/fonts", true);
PD4PageMark footer = new PD4PageMark();
footer.setHtmlTemplate("<div style=\"font-family:宋体;font-size:8px;text-align:center;width:100%\">第 $[page] 页 共 $[total] 页</div>");
footer.setAreaHeight(-1);
pd4ml.setPageFooter(footer);
pd4ml.render(strReader, fos);
}
public StringBuffer getHtml(Object in){
StringBuffer html = new StringBuffer();
html.append("<html>")
.append("<head>")
.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />")
.append("<style>")
.append("BODY {PADDING-BOTTOM: 0px; LINE-HEIGHT: 1.5; FONT-STYLE: normal; MARGIN: 0px; PADDING-LEFT: 0px; PADDING-RIGHT: 0px; COLOR: #333; FONT-SIZE: 13px; FONT-WEIGHT: normal; PADDING-TOP: 0px}")
.append("table{border:1px solid #000;}")
.append("table td{border:1px solid #000;}")
.append("</style>")
.append("</head>")
.append("<body>");
html.append(in);
html.append("</body></html>");
return html;
}
private void PrintPDF(File pdFile) {
//构建打印请求属性集
HashPrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
//设置打印格式,如未确定类型,选择autosense
DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
//查找所有的可用的打印服务
// PrintService printService[] = PrintServiceLookup.lookupPrintServices(flavor, pras);
//定位默认的打印服务
PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
//显示打印对话框
// PrintService service = ServiceUI.printDialog(null, 200, 200, printService,defaultService, flavor, pras);
if(defaultService != null){
try {
DocPrintJob job = defaultService.createPrintJob();//创建打印作业
FileInputStream fis = new FileInputStream(pdFile);//构造待打印的文件流
DocAttributeSet das = new HashDocAttributeSet();
Doc doc = new SimpleDoc(fis, flavor, das);
job.print(doc, pras);
} catch (Exception e){
e.printStackTrace();
}
}
}
关于从XML或HTML生成PDF文件和xml转成html的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于C#使用wkhtmltopdf,把HTML生成PDF(包含分页)、C#编写 HTML生成PDF、html生成pdf、java html生成PDF,并打印等相关内容,可以在本站寻找。
本文标签: