Как создать PDF из HTML, хранящегося в строке из базы данных, используя itextsharp - PullRequest
0 голосов
/ 02 августа 2010

Мне нужно создать PDF-файл из HTML-кода, предоставленного из базы данных, который был сохранен в редакторе ...

Мне нужно показать соответствующий HTML-код со всеми стилями в PDF-файле ... пожалуйста, помогите

Я использую метод itextsharp, но я не получаю правильный контент, который я предоставлял в редакторе при преобразовании его в pdf,

Код, который я использовал

    string content = "<the html content from database>";

    StringReader reader = new StringReader(content);
    MemoryStream ms = new MemoryStream();
    Document doc = new Document(PageSize.A4,50,50,30,30);
    HTMLWorker parser = new HTMLWorker(doc);
    PdfWriter.GetInstance(doc, ms);
    doc.Open();
    try
    {
        parser.Parse(reader);
    }
    catch(Exception ex)
    {
        Paragraph paragraph = new Paragraph("Error! " + ex.Message);
        paragraph.SetAlignment("center");
        Chunk text = paragraph.Chunks[0] as Chunk;
        doc.Add(paragraph);
    }
    finally
    {
        doc.Close();
    }
    Byte[] buffer = ms.GetBuffer();
    if (buffer != null)
    {
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-length", buffer.Length.ToString());
        Response.BinaryWrite(buffer);
    }

- эточто-то не так в этом, пожалуйста, помогите с кодом создать PDF из HTML

1 Ответ

0 голосов
/ 02 августа 2010

Вот код, который работает для меня.

     using System;
     using System.Collections.Generic;
     using System.Linq;
     using System.Web;
     using System.Web.UI;
     using System.Web.UI.WebControls;
     using iTextSharp.text;
     using iTextSharp.text.pdf;
     using System.IO;
     using System.Collections;
     using System.Text;
     using iTextSharp.text.xml;
     using iTextSharp.text.html;

     public partial class Default2 : System.Web.UI.Page
     {
           protected void Page_Load(object sender, EventArgs e)
           {
            //create document
            Response.Write(Server.MapPath("."));
            Document document = new Document();
            try
            {
              //writer - have our own path!!!
               PdfWriter.GetInstance(document, new FileStream(Server.MapPath(".") +         
                  "parsetest.pdf", FileMode.Create));
        document.Open();
        //html -text - kan be from database or editor too
        String htmlText = "<font  " +
        " color=\"#0000FF\"><b><i>Title One</i></b></font><font   " +
        " color=\"black\"><br><br>Some text here<br><br><br><font   " +
        " color=\"#0000FF\"><b><i>Another title here   " +
        " </i></b></font><font   " +
        " color=\"black\"><br><br>Text1<br>Text2<br><OL><LI>hi</LI><LI>how are u</LI> 
        </OL>";
        //make an arraylist ....with STRINGREADER since its no IO reading file...
        List<IElement> htmlarraylist = iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(new StringReader(htmlText), null);

        //add the collection to the document
        for (int k = 0; k < htmlarraylist.Count; k++)
        {
            document.Add((IElement)htmlarraylist[k]);
        }
        document.Add(new Paragraph("And the same with indentation...."));
        // or add the collection to an paragraph
        // if you add it to an existing non emtpy paragraph it will insert it from
        //the point youwrite -
        Paragraph mypara = new Paragraph();//make an emtphy paragraph as "holder"
        mypara.IndentationLeft = 36;
        mypara.InsertRange(0, htmlarraylist);
        document.Add(mypara);
        document.Close();

    }
    catch (Exception exx)
    {
        Console.Error.WriteLine(exx.StackTrace);
        Console.Error.WriteLine(exx.Message);
    }
 }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...