[英]Html to PDF ITextSharp Image
我正在使用ITextSharp將HTML轉換為PDF,當我嘗試將圖像插入HTML頁面時出現問題,但是當下載PDF時卻看不到其中的圖像。 我沒有看到任何錯誤,代碼可以正常工作,但是在下載的PDF中看不到圖像。 PDF的路徑是正確的,因為它可以在HTML PAGE中使用,我什至嘗試使用HTML更改圖像和畫布的尺寸,但這並不能解決問題。
將HTML轉換為PDF的編碼是:
public void DownloadAsPDF()
{
try
{
string case_id = Request.Form["case_id"];
string strHtml = string.Empty;
string pdfFileName = Request.PhysicalApplicationPath + "\\files\\" + case_id + ".pdf";
string template = System.IO.File.ReadAllText(Server.MapPath("~/Incomplete-Pdf-temp.html"));
插入圖像開始的代碼
Base64ToImage().Save(Server.MapPath("\\files\\" + case_id + "stu.jpg"));
Base64ToInsImage().Save(Server.MapPath("\\files\\" + case_id + "ins.jpg"));
string facultysign = "/files/CS00022904stu.jpg";
string stusign = "/files/CS00022904stu.jpg";
template = template.Replace("[stusign]", facultysign);
template = template.Replace("[facultysign]", stusign);
插入圖像結尾的代碼
CreatePDFFromHTMLFile(template, pdfFileName);
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
public void CreatePDFFromHTMLFile(string HtmlStream, string FileName)
{
try
{
object TargetFile = FileName;
string ModifiedFileName = string.Empty;
string FinalFileName = string.Empty;
GeneratePDF.HtmlToPdfBuilder builder = new GeneratePDF.HtmlToPdfBuilder(iTextSharp.text.PageSize.A4);
GeneratePDF.HtmlPdfPage first = builder.AddPage();
first.AppendHtml(HtmlStream);
byte[] file = builder.RenderPdf();
System.IO.File.WriteAllBytes(TargetFile.ToString(), file);
iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(TargetFile.ToString());
ModifiedFileName = TargetFile.ToString();
ModifiedFileName = ModifiedFileName.Insert(ModifiedFileName.Length - 4, "1");
iTextSharp.text.pdf.PdfEncryptor.Encrypt(reader, new FileStream(ModifiedFileName, FileMode.Append), iTextSharp.text.pdf.PdfWriter.STRENGTH128BITS, "", "", iTextSharp.text.pdf.PdfWriter.AllowPrinting);
reader.Close();
if (System.IO.File.Exists(TargetFile.ToString()))
System.IO.File.Delete(TargetFile.ToString());
FinalFileName = ModifiedFileName.Remove(ModifiedFileName.Length - 5, 1);
System.IO.File.Copy(ModifiedFileName, FinalFileName);
if (System.IO.File.Exists(ModifiedFileName))
System.IO.File.Delete(ModifiedFileName);
}
catch (Exception ex)
{
throw ex;
}
}
* HMTL編碼以插入圖像*
<p><strong>Faculty Signature: </strong></p>
<img src='[stusign]' />
<p><strong>Faculty Signature: </strong></p>
<img src='[facultysign]' />
調整圖像大小可以為我解決問題(即使調整畫布大小也可以解決問題)。
后面代碼中的pdfptable和pdfpcell可用於定位PDF中的圖像。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.