How I can use a html file with styles for creat a pdf file with iTextSharp

北城以北 提交于 2019-12-11 19:00:03

问题


Hi I want to create a pdf in my ASP.NET Application and for this I use iTextSharp. My idea is it to create a pdf out of a HTML file. I want that if I click on a Button I read a HTML file with a background-image and much styles.

My Application must do..

  1. Read a HTML file from the Folder App.Data. (using System.IO)
  2. Create a PDF out of this HTML file with this styles! (using iTextSharp.text; using iTextSharp.text.pdf;) 3.send the PDF file as email. (using System.Net.Mail;using System.Net.Mime;)

I try to create a PDF and if work but if I use styles in my HTML file it doesn't show the styles :(

here is my code:

string html;

using (StreamReader reader = new StreamReader(Server.MapPath("~/App_Data/mail.html"), System.Text.Encoding.Default))
{
    html = reader.ReadToEnd(); //here i read the html file to this string
    HTMLtoPdf(html);
}

private void HTMLtoPdf(string HTML) 
{
    Document doc = new Document();
    PdfWriter.GetInstance(doc, new FileStream(Request.PhysicalApplicationPath + "\\test.pdf", FileMode.Create));
    doc.Open();
    HTMLWorker hw = new HTMLWorker(doc);
    hw.Parse(new StringReader(HTML));
    doc.Close();

    ShowPdf("test.pdf");
}

private void ShowPdf(string s)
{
    Response.ClearContent();
    Response.ClearHeaders();
    Response.AddHeader("Content-Disposition", "inline;filename=" + s);
    Response.ContentType = "application/pdf";
    Response.WriteFile(s);
    Response.Flush();
    Response.Clear();
}

For example my HTML file:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html><head>

</head><body styles="background-color:#E0E0E0; font-weight:bold; font-family:Arial; font-size:120%;">

<div>
    Test
</div>

</body></html> 

In this Example I use background color but it don't work :( I get only the HTML text : test without styles.


回答1:


You've spelled "style" wrong.

<body styles="background-color:#E0E0E0;

It Should be

<body style="background-color:#E0E0E0;



回答2:


you should use bgcolor here instead of background-color



来源:https://stackoverflow.com/questions/14703231/how-i-can-use-a-html-file-with-styles-for-creat-a-pdf-file-with-itextsharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!