我想使用Pechkin将aspx转换为PDF。在文本框中插入的值不是pdf我应该怎么做才能在pdf中获取插入的值
我的aspx页面包含图片,文本框,标签。
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
try
{
string html;
if (string.IsNullOrEmpty(tbUrl.Text.Trim()))
{
throw new ApplicationException("The URL is empty.");
}
using (var client = new WebClient())
{
html = client.DownloadString(tbUrl.Text);
}
//Transform the HTML into PDF
var pechkin = Factory.Create(new GlobalConfig());
var pdf = pechkin.Convert(new ObjectConfig()
.SetLoadImages(true).SetZoomFactor(1.5)
.SetPrintBackground(true)
.SetScreenMediaType(true)
.SetCreateExternalLinks(true), html);
//Return the PDF file
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", string.Format("attachment;filename=test.pdf; size={0}", pdf.Length));
Response.BinaryWrite(pdf);
Response.Flush();
Response.End();
}
catch (Exception ex)
{
}
}
答案 0 :(得分:1)
您需要将页面网址转换为URI,然后再将其发送到转换器。
将您的错误行更改为:
htmlToPdf.Run(new Uri(sbHtml.ToString(), UriKind.Relative)));
您将url作为普通字符串发送,这使得转换器认为它是HTML字符串,因此在尝试转换它时,它在开头就遇到了“错误”,因为它不是有效的html字符串。 / p>
<强>更新强>
如果上述方法无效,请使用绝对路径。
首先,使用Server.MapPath
映射页面的绝对路径:
string absolutePagePath = Server.MapPath("Contractor1.aspx");
然后将其发送到pdfizer:
htmlToPdf.Run(new Uri(absolutePagePath));
答案 1 :(得分:0)
您正在传递Page URL
而不是Html字符串..
<强> sbHtml.Append("Contractor1.aspx");
强>
您必须先创建html并将其传递给sbHtml
string ..
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
string sPathToWritePdfTo = @"C:\new_pdf_name.pdf";
System.Text.StringBuilder sbHtml = new System.Text.StringBuilder();
sbHtml.Append("Contractor1.aspx"); // you have to pass HTML string here
using (System.IO.Stream stream = new System.IO.FileStream(sPathToWritePdfTo, System.IO.FileMode.OpenOrCreate))
{
Pdfizer.HtmlToPdfConverter htmlToPdf = new Pdfizer.HtmlToPdfConverter();
htmlToPdf.Open(stream);
htmlToPdf.Run(sbHtml.ToString());//error
htmlToPdf.AddChapter("Mobily");
htmlToPdf.Close();
}
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "mobily.pdf"));
HttpContext.Current.Response.ContentType = "application/pdf";
HttpContext.Current.Response.WriteFile(sPathToWritePdfTo);
HttpContext.Current.Response.End();
}