developer tip

ITextSharp HTML을 PDF로?

copycodes 2020. 11. 27. 08:21
반응형

ITextSharp HTML을 PDF로?


ITextSharp에 HTML을 PDF로 변환하는 기능이 있는지 알고 싶습니다. 내가 변환 할 모든 것은 일반 텍스트 일 ​​뿐이지 만 안타깝게도 ITextSharp에 대한 문서가 거의 또는 전혀 없기 때문에 이것이 저에게 실행 가능한 솔루션인지 결정할 수 없습니다.

그렇게 할 수 없다면 누군가가 간단한 일반 텍스트 HTML 문서를 가져 와서 pdf로 변환 할 수있는 좋은 무료 .net 라이브러리를 알려줄 수 있습니까?

티아.


나는 몇 주 전에 같은 질문을 보았는데 이것이 내가 찾은 결과입니다. 이 방법은 HTML을 PDF로 빠르게 덤프합니다. 문서는 형식 조정이 필요합니다.

private MemoryStream createPDF(string html)
{
    MemoryStream msOutput = new MemoryStream();
    TextReader reader = new StringReader(html);

    // step 1: creation of a document-object
    Document document = new Document(PageSize.A4, 30, 30, 30, 30);

    // step 2:
    // we create a writer that listens to the document
    // and directs a XML-stream to a file
    PdfWriter writer = PdfWriter.GetInstance(document, msOutput);

    // step 3: we create a worker parse the document
    HTMLWorker worker = new HTMLWorker(document);

    // step 4: we open document and start the worker on the document
    document.Open();
    worker.StartDocument();

    // step 5: parse the html into the document
    worker.Parse(reader);

    // step 6: close the document and the worker
    worker.EndDocument();
    worker.Close();
    document.Close();

    return msOutput;
}

몇 가지 파기를 한 후 ITextSharp로 필요한 것을 달성하는 좋은 방법을 찾았습니다.

향후 다른 사람에게 도움이 될 경우 다음과 같은 샘플 코드가 있습니다.

protected void Page_Load(object sender, EventArgs e)
{
    Document document = new Document();
    try
    {
        PdfWriter.GetInstance(document, new FileStream("c:\\my.pdf", FileMode.Create));
        document.Open();
        WebClient wc = new WebClient();
        string htmlText = wc.DownloadString("http://localhost:59500/my.html");
        Response.Write(htmlText);
        List<IElement> htmlarraylist = HTMLWorker.ParseToList(new StringReader(htmlText), null);
        for (int k = 0; k < htmlarraylist.Count; k++)
        {
            document.Add((IElement)htmlarraylist[k]);
        }

        document.Close();
    }
    catch
    {
    }
}

다음은 asp.net mvc 컨트롤러에서 pdf 응답을 반환하기 위해 버전 5.4.2 (nuget 설치에서)에서 작업 할 수 있었던 것입니다. 필요한 경우 출력에 MemoryStream 대신 FileStream을 사용하도록 수정할 수 있습니다.

html-> pdf 변환에 대한 현재 iTextSharp 사용의 완전한 예이기 때문에 여기에 게시합니다 (이미지는 무시하고 내 사용에 필요하지 않기 때문에 보지 않았습니다).

iTextSharp의 XmlWorkerHelper를 사용하므로 들어오는 hmtl이 유효한 XHTML이어야하므로 입력에 따라 수정해야 할 수도 있습니다.

using iTextSharp.text.pdf;
using iTextSharp.tool.xml;
using System.IO;
using System.Web.Mvc;

namespace Sample.Web.Controllers
{
    public class PdfConverterController : Controller
    {
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult HtmlToPdf(string html)
        {           

            html = @"<?xml version=""1.0"" encoding=""UTF-8""?>
                 <!DOCTYPE html 
                     PUBLIC ""-//W3C//DTD XHTML 1.0 Strict//EN""
                    ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"">
                 <html xmlns=""http://www.w3.org/1999/xhtml"" xml:lang=""en"" lang=""en"">
                    <head>
                        <title>Minimal XHTML 1.0 Document with W3C DTD</title>
                    </head>
                  <body>
                    " + html + "</body></html>";

            var bytes = System.Text.Encoding.UTF8.GetBytes(html);

            using (var input = new MemoryStream(bytes))
            {
                var output = new MemoryStream(); // this MemoryStream is closed by FileStreamResult

                var document = new iTextSharp.text.Document(iTextSharp.text.PageSize.LETTER, 50, 50, 50, 50);
                var writer = PdfWriter.GetInstance(document, output);
                writer.CloseStream = false;
                document.Open();

                var xmlWorker = XMLWorkerHelper.GetInstance();
                xmlWorker.ParseXHtml(writer, document, input, null);
                document.Close();
                output.Position = 0;

                return new FileStreamResult(output, "application/pdf");
            }
        }
    }
}

평판이 있으면 mayymada의 대답을 한 번 더 할 것입니다. 방금 Pechkin을 사용하여 asp.net HTML to PDF 솔루션을 구현했습니다. 결과는 훌륭합니다.

Pechkin에 대한 너겟 패키지가 있지만 위의 포스터가 그의 블로그에서 언급했듯이 ( http://codeutil.wordpress.com/2013/09/16/convert-html-to-pdf/- 나는 그녀가 신경 쓰지 않기를 바랍니다. 다시 게시),이 분기에서 수정 된 메모리 누수가 있습니다.

https://github.com/tuespetre/Pechkin

위 블로그에는이 패키지를 포함하는 방법에 대한 특정 지침이 있습니다 (32 비트 dll이며 .net4 필요). 여기 내 코드입니다. 들어오는 HTML은 실제로 HTML Agility Pack을 통해 조립됩니다 (인보이스 생성을 자동화하고 있습니다).

public static byte[] PechkinPdf(string html)
{
  //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
  return pdf;
}

다시, mayymada 감사합니다-당신의 대답은 환상적입니다.


I prefer using another library called Pechkin because it is able to convert non trivial HTML (that also has CSS classes). This is possible because this library uses the WebKit layout engine that is also used by browsers like Chrome and Safari.

I detailed on my blog my experience with Pechkin: http://codeutil.wordpress.com/2013/09/16/convert-html-to-pdf/


The above code will certainly help in converting HTML to PDF but will fail if the the HTML code has IMG tags with relative paths. iTextSharp library does not automatically convert relative paths to absolute ones.

I tried the above code and added code to take care of IMG tags too.

You can find the code here for your reference: http://www.am22tech.com/html-to-pdf/


It has ability to convert HTML file in to pdf.

Required namespace for conversions are:

using iTextSharp.text;
using iTextSharp.text.pdf;

and for conversion and download file :

// Create a byte array that will eventually hold our final PDF
Byte[] bytes;

// Boilerplate iTextSharp setup here

// Create a stream that we can write to, in this case a MemoryStream
using (var ms = new MemoryStream())
{
    // Create an iTextSharp Document which is an abstraction of a PDF but **NOT** a PDF
    using (var doc = new Document())
    {
        // Create a writer that's bound to our PDF abstraction and our stream
        using (var writer = PdfWriter.GetInstance(doc, ms))
        {
            // Open the document for writing
            doc.Open();

            string finalHtml = string.Empty;

            // Read your html by database or file here and store it into finalHtml e.g. a string
            // XMLWorker also reads from a TextReader and not directly from a string
            using (var srHtml = new StringReader(finalHtml))
            {
                // Parse the HTML
                iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, srHtml);
            }

            doc.Close();
        }
    }

    // After all of the PDF "stuff" above is done and closed but **before** we
    // close the MemoryStream, grab all of the active bytes from the stream
    bytes = ms.ToArray();
}

// Clear the response
Response.Clear();
MemoryStream mstream = new MemoryStream(bytes);

// Define response content type
Response.ContentType = "application/pdf";

// Give the name of file of pdf and add in to header
Response.AddHeader("content-disposition", "attachment;filename=invoice.pdf");
Response.Buffer = true;
mstream.WriteTo(Response.OutputStream);
Response.End();

If you are converting html to pdf on the html server side you can use Rotativa :

Install-Package Rotativa

This is based on wkhtmltopdf but it has better css support than iTextSharp has and is very simple to integrate with MVC (which is mostly used) as you can simply return the view as pdf:

public ActionResult GetPdf()
{
    //...
    return new ViewAsPdf(model);// and you are done!
} 

참고URL : https://stackoverflow.com/questions/2822843/itextsharp-html-to-pdf

반응형