Asp.net mvc uses ITextSharp PDF to HTML (solves the img tag problem) and mvcitextsharp

Source: Internet
Author: User
Tags baseuri

Asp.net mvc uses ITextSharp PDF to HTML (solves the img tag problem) and mvcitextsharp

HTML code must be converted to PDF for project requirements. Basically, it has been implemented. It can be found that when ITextSharp (my current version is 5.5.9) is used, the src In the img label can only follow the absolute path.

I searched for a morning on Baidu and found no associated solutions. Finally, I went to Google for help and finally found it.

This is original article: http://www.am22tech.com/html-to-pdf/ (may need FQ)

This is an example I have summarized (the second solution is used ):

Don't understand can also refer to my blog: http://www.cnblogs.com/zuochengsi-9/p/5483808.html

Body:

I am looking for perfect examples everywhere, but none of them can solve my needs perfectly. My requirements are very simple, as follows:

Create a PDF document from an HTML page. The code in this HTML contains the img tag and the relative path used at the same time.

I found valuable places from these places http://kuujinbo.info/iTextSharp/tableWithImageToPdf.aspx

And http://hamang.net/2008/08/14/html-to-pdf-in-net/

Finally, the following asp.net code can be used to solve my problem. I hope this will also help you!

Prerequisites:

Download and copy iTextSharp. dll my version is 5.1.1

Problems and Solutions:

This new ITextSharp library is good for converting HTML code to PDF. However, there is a major defect that the image URL ing can only be an absolute path.

Otherwise, the HTMLworlker class will throw an exception if you use the relative path.

There are two solutions for this problem:

1. Use the IImageProvider interface to retrieve all images from the HTML code and then "paste" PDF.

However, the img-modified style in HTML code, such as height and width, is not retained.

2. parse the HTML code and replace the relative URL with an absolute URL before writing the PDF file.

This method saves the height and width set with in the HTML code. Of course, this method is better.

However, I still provide two solutions for you to choose.

Basic preparations:

Add a new page in your code

Postto1__am22.aspx

Postto1__am22.aspx.cs

Method 1:

 

Using System; using System. collections. generic; using System. linq; using System. web; using System. web. UI; using System. web. UI. webControls; // reference using iTextSharp for HTML to PDF. text; using iTextSharp.text.html; using iTextSharp.text.pdf; using iTextSharp. text. xml; using iTextSharp.text.html. simpleparser; using System. IO; using System. util; using System. text. regularExpressions; // For converting HTML PDF-END public partial class postto1__am22: System. web. UI. page {protected void Page_Load (object sender, EventArgs e) {// Get the HTML code from your database or whereever you have stored it and store // it in HTMLCode variable. string HTMLCode = string. empty; ConvertHTMLToPDF (HTMLCode);} protected void ConvertHTMLToPDF (string HTMLCode) {HttpContext context = HttpContext. current; // Render Pla CeHolder to temporary stream System. IO. stringWriter stringWrite = new StringWriter (); System. web. UI. htmlTextWriter htmlWrite = new HtmlTextWriter (stringWrite); StringReader reader = new StringReader (HTMLCode); // Create PDF document Document doc = new Document (PageSize. a4); HTMLWorker parser = new HTMLWorker (doc); extends writer. getInstance (doc, new FileStream (Server. mapPath ("~ ") +"/App_Data/HTMLToPDF.pdf ", FileMode. create); doc. open (); /*************************************** **************************************** */var interfaceProps = new Dictionary <string, object> (); var ih = new ImageHander () {BaseUri = Request. url. toString ()}; interfaceProps. add (HTMLWorker. IMG_PROVIDER, ih); foreach (IElement element in HTMLWorker. parseToList (new StringReader (HTMLCode), null) {doc. add (element);} doc. close (); Response. end (); /*************************************** **************************************** * /} // handle Image relative and absolute URL's public class ImageHander: IImageProvider {public string BaseUri; public iTextSharp. text. image GetImage (string src, IDictionary <string, string> h, ChainedProperties cprops, IDocListener doc) {string imgPath = string. empty; if (src. toLower (). contains ("http: //") = false) {imgPath = HttpContext. current. request. url. scheme + ": //" + HttpContext. current. request. url. authority + src;} else {imgPath = src;} return iTextSharp. text. image. getInstance (imgPath );}}}

 

Method 2:

using System;    using System.Collections.Generic;    using System.Linq;    using System.Web;    using System.Web.UI;    using System.Web.UI.WebControls;    //For converting HTML TO PDF- START    using iTextSharp.text;    using iTextSharp.text.html;    using iTextSharp.text.pdf;    using iTextSharp.text.xml;    using iTextSharp.text.html.simpleparser;    using System.IO;    using System.util;    using System.Text.RegularExpressions;    //For converting HTML TO PDF- END    public partial class PostToPDF_AM22 : System.Web.UI.Page    {    protected void Page_Load(object sender, EventArgs e)    {    //Get the HTML code from your database or whereever you have stored it and store    //it in HTMLCode variable.    string HTMLCode = string.Empty;    ConvertHTMLToPDF(HTMLCode);    }    protected void ConvertHTMLToPDF(string HTMLCode)    {    HttpContext context = HttpContext.Current;    //Render PlaceHolder to temporary stream    System.IO.StringWriter stringWrite = new StringWriter();    System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);    /********************************************************************************/    //Try adding source strings for each image in content    string tempPostContent = getImage(HTMLCode);    /*********************************************************************************/    StringReader reader = new StringReader(tempPostContent);    //Create PDF document    Document doc = new Document(PageSize.A4);    HTMLWorker parser = new HTMLWorker(doc);    PdfWriter.GetInstance(doc, new FileStream(Server.MapPath("~") + "/App_Data/HTMLToPDF.pdf",    FileMode.Create));    doc.Open();    try    {    //Parse Html and dump the result in PDF file    parser.Parse(reader);    }    catch (Exception ex)    {    //Display parser errors in PDF.    Paragraph paragraph = new Paragraph("Error!" + ex.Message);    Chunk text = paragraph.Chunks[0] as Chunk;    if (text != null)    {    text.Font.Color = BaseColor.RED;    }    doc.Add(paragraph);    }    finally    {    doc.Close();    }    }    public string getImage(string input)    {    if (input == null)    return string.Empty;    string tempInput = input;    string pattern = @"

Note:

The preceding two solutions have a ConvertHTMLToPDF method, which requires the HTML code format. For details, visit the ITextSharp official website.

The name of a document whose final result is stored is htmltow.w.gov.cn in the App_Data folder of your website.

Remember, you need to write code to get the HTML code from your database or other files in the above Page_Load event.

The HTML code conversion function creates a PDF file for you.

If you have any questions, write them in the comments and I will try my best to help you.

------------------------------------------------------

For the first translation, the original translation is used directly. However, this time I feel that reading English documents is not as resistant as before. If you try again, you will get something!

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.