html实现pdf预览打印机,Pdf操作(HTML转PDF,PDF直接网页连接打印机)

本文介绍了如何通过引用TuesPechkin.dll和TuesPechkin.Wkhtmltox.AnyCPU.dll将Web页面内容转换为PDF,包括创建wkhtmltopdf路径、处理HTML模板和内容、并实现浏览器链接打印。展示了使用C#进行Web表单到PDF的完整过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Pdf导出的操作:引用TuesPechkin.dll和TuesPechkin.Wkhtmltox.AnyCPU.dll程序集,新建PDF静态类 PDFConverter,在web.config配置保存dir

///

///pdf转换///

public static classPdfConvert {///

///staticDeploymentPath///

private static readonly string StaticDeploymentPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "wkhtmltopdf");///

///CreateWkhtmltopdfPath///

public static voidCreateWkhtmltopdfPath() {if (Directory.Exists(StaticDeploymentPath) == false) {

Directory.CreateDirectory(StaticDeploymentPath);

}

}///

///converter///

public static IConverter Converter =

newThreadSafeConverter(new RemotingToolset(newWinAnyCPUEmbeddedDeployment(newStaticDeployment(StaticDeploymentPath)

)

)

);

}

publicHttpResponseMessage CreateFormPdf(WebTaskFormDetail wtData) {try{string fileName = AesCode.AesDecrypt(wtData.TaskId) + "_" +wtData.FormId;var baseUrl =GetBaseUrl();string url = baseUrl +UrlFormTemplate;

HttpClient client= newHttpClient();var template =client.GetStringAsync(url).Result;string page = "form.html";

url= baseUrl + UrlFormContentDir +page;var content =client.GetStringAsync(url).Result;var json = JsonConvert.SerializeObject(wtData).Replace(@"\", @"\\");string html = template.Replace("[[content]]", content).Replace("[[json]]", json);string path = HttpContext.Current.Request.PhysicalApplicationPath + ZxjcAttachmentDir + @"html\";if (!Directory.Exists(path)) {

Directory.CreateDirectory(path);

}

StreamWriter sw= new StreamWriter(path + fileName + ".html", false, Encoding.UTF8);

sw.Write(html);

sw.Close();

path= ZxjcAttachmentDir + @"pdf\";if (!Directory.Exists(Path.Combine(PhysicalApplicationPath(), path))) {

Directory.CreateDirectory(Path.Combine(PhysicalApplicationPath(), path));

}var savePath = path + fileName + ".pdf";byte[] pdfBuf = null;

CreatePdf(Path.Combine(PhysicalApplicationPath(), savePath), fileName,refpdfBuf);var downloadUrl = new Uri(baseUrl + ZxjcAttachmentDir.Replace(@"\", "/") + "pdf/" + fileName + ".pdf");//关联任务附件

var attachmentInfo = newAttachmentInfo {

AttachmentName= wtData.FormName + ".pdf",

Path=savePath,

Url=downloadUrl.ToString(),

Description=wtData.Description

};

SaveAttachment(attachmentInfo,Convert.ToInt32(AesCode.AesDecrypt(wtData.TaskId)));

HttpResponseMessage response= new HttpResponseMessage { Content = new StreamContent(newMemoryStream(pdfBuf)) };

response.Content.Headers.ContentDisposition= new ContentDispositionHeaderValue("attachment");

response.Content.Headers.ContentLocation=downloadUrl;

response.Content.Headers.ContentType= new MediaTypeHeaderValue("application/pdf");returnresponse;

}catch(Exception ex) {throw;

}

}private void CreatePdf(string path, string fileName, ref byte[] pdfBuf) {var document = newHtmlToPdfDocument {

GlobalSettings={

ProduceOutline= true,

DocumentTitle= "web 表单",

PaperSize=PaperKind.A4,

Margins={All = 1.375,Unit =Unit.Centimeters}//Margins = new MarginSettings(50,50,50,50)

},

Objects={new ObjectSettings { PageUrl = this.GetBaseUrl() + ZxjcAttachmentDir.Replace(@"\", "/") + "html/" + fileName + ".html"}

}

};

pdfBuf=PdfConvert.Converter.Convert(document);

File.WriteAllBytes(path, pdfBuf);

}private static stringPhysicalApplicationPath() {returnHttpContext.Current.Request.PhysicalApplicationPath;

}

直接在浏览器链接打印机打印

private void CreatePdf(string path, string fileName, ref byte[] pdfBuf) {

var pageUrl = this.GetBaseUrl() + ZxjcAttachmentDir.Replace(@"\", "/") + "html/" + fileName + ".html";

var document = new HtmlToPdfDocument {

GlobalSettings ={

ProduceOutline = true,

Copies=1,

DPI = 1200,

DocumentTitle = "web 表单",

PaperSize = PaperKind.A4,

Orientation = GlobalSettings.PaperOrientation.Portrait,

OutputFormat = GlobalSettings.DocumentOutputFormat.PDF,

Margins ={All = 1.375,Unit = Unit.Centimeters}

//Margins = new MarginSettings(50,50,50,50)

},

Objects = {

new ObjectSettings {

PageUrl = pageUrl,

//HtmlText = docHtml,

WebSettings = new WebSettings {

DefaultEncoding = "utf-8",

LoadImages =true,

PrintBackground =true,

EnableJavascript =true ,

PrintMediaType =true,

EnablePlugins = true

},

//LoadSettings =new LoadSettings {

// BlockLocalFileAccess = false,

// RenderDelay=5000,

//}

}

}

};

pdfBuf = PdfConvert.Converter.Convert(document);

File.WriteAllBytes(path, pdfBuf);

}

1、解决中文问题 2、附字体 3、动态html拼接pdf public static void htmlCodeComeString(String linkcss,String htmlCode, String outputFile,String title) throws Exception { OutputStream os = new FileOutputStream(outputFile); ITextRenderer renderer = new ITextRenderer(); renderer.setDocumentFromString(getConversionHtmlCode(linkcss,htmlCode,title)); ITextFontResolver fontResolver = renderer.getFontResolver(); URL fontPath = ItextUtil.class.getResource("simsun.ttc"); fontResolver.addFont(fontPath.toString(), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); // 解决图片的相对路径问题 // renderer.getSharedContext().setBaseURL("file:/F:/teste/html/"); renderer.layout(); renderer.createPDF(os); System.out.println("======换成功!"); os.close(); os.flush(); } public static void main(String[] args) { ItextUtil itextUtil = new ItextUtil(); String html = ""; html += ""; html += "企业信息"; html += " "; html += " "; html += " 登记日期"; html += " 2006-04-28"; html += " "; html += " "; html += " 纳税人编号"; html += " HSJIHKS002"; html += " "; html += " "; html += " 有效标志"; html += " Y"; html += " "; html += " "; html += " 社会信用代码"; html += " 916101317H"; html += " "; html += " "; html += " 评估机关代码"; html += " 盛世"; html += " "; html += " "; html += " 工商注销日期"; html += " 2006-04-28"; html += " "; html += " "; html += ""; String outputFile = "D:\\pdf\\aa.pdf"; try { itextUtil.htmlCodeComeString("",html,outputFile,""); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("生成结束!!!"); }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值