Html2pdf Web to PDF

Source: Internet
Author: User

Gayhub Links

Ask all over Google Baidu, still no good plan.

Open Gayhub, found praise be JS effect is that xx kind, a confused img posing fine pdf?

After a day of thinking, with the help of hiqpdf (estimate Itext, spirepdf and other similar can, the idea also use this can), and finally realized the most perfect solution at present-and, thief simple you believe?

First one (= ̄ω ̄=)

Simple version, read the file-the advantage is to disregard the website customization, the disadvantage of course is non-automation (,, ω,,)

In your backstage put a receiver, java,golang,python version of the, another day lazy cancer relieved on the supplement:

        Public ActionResult Getwow () {FileStream fs = new FileStream (Server.MapPath ("/app_data/wow.txt"            ), FileMode.OpenOrCreate, FileAccess.Read);//path StreamReader sr = new StreamReader (FS, Encoding.UTF8); var htm = Sr.            ReadToEnd (); Sr.            Close (); Fs.            Close ();            Create the HTML to PDF converter htmltopdf htmltopdfconverter = new Htmltopdf ();            Set browser width htmltopdfconverter.browserwidth = 1440; Set browser height if specified, otherwise use the default Htmltopdfconverter.browserheight = Htmltopdfconve Rter.            Browserwidth * 2; Set HTML Load Timeout//htmltopdfconverter.htmlloadedtimeout = Int.            Parse (Textboxloadhtmltimeout.text); Set PDF page size and orientation//htmltopdfconverter.document.pagesize = new Pdfpagesize ((float) (WIDTH/2            .4), (float) (height/2.4)); HtmlToPdfConverter.Document.PageSizE = new Pdfpagesize (htmltopdfconverter.browserwidth, htmltopdfconverter.browserheight);            HtmlToPdfConverter.Document.PageOrientation = pdfpageorientation.portrait; Set the PDF standard used by the document HtmlToPdfConverter.Document.PdfStandard = PDFSTANDARD.PDF;//CHECKB Oxpdfa.checked?            PDFSTANDARD.PDFA://Set PDF page margins htmlToPdfConverter.Document.Margins = new Pdfmargins (0);            Set whether to embed the true Type font in PDF htmlToPdfConverter.Document.FontEmbedding = true; Set triggering mode;             For WaitTime mode set the wait time before convert htmltopdfconverter.triggermode = Conversiontriggermode.auto;            Set Header and Footer//setheader (htmltopdfconverter.document);            Setfooter (htmltopdfconverter.document);  Set the document security//htmltopdfconverter.document.security.openpassword = Textboxopenpassword.text;          HtmlToPdfConverter.Document.Security.AllowPrinting = true; Set the permissions password too if an open password is set if (htmlToPdfConverter.Document.Security.OpenPa ssWOrd! = NULL && HtmlToPdfConverter.Document.Security.OpenPassword! = String.Empty) htmltopdfconve Rter.            Document.Security.PermissionsPassword = HtmlToPdfConverter.Document.Security.OpenPassword + "_admin";            Cursor = Cursors.waitcursor;            Convert HTML to PDF string pdffile = null;            Convert URL to a PDF memory buffer//string URL = formcollection["Textboxurl"];            byte[] Pdfbuffer = htmltopdfconverter.converthtmltomemory (htm, null); Send the PDF document to browser Fileresult Fileresult = new Filecontentresult (Pdfbuffer, "application/pdf")            ;            Fileresult.filedownloadname = "Htmltopdf.pdf"; Return File (Pdfbuffer, "Application/octet-stream", "test.pdf");//LastDouble quotes inside is the callback file name, add a time value can avoid repetition} 

Press F12 to open console input in the browserdocument.getElementsByTagName("html")[0].innerHTML

Copy the resulting string to the path save

Then run the server and activate the controller "http://localhost:3095/".

Then you'll download a PDF, open it, and get excited?

Advanced version--front and back interaction

    1. Controller:
        Public ActionResult getpdffromhtmlcode (int width, int height, string htm) {htm = Server.urldeco            De (HTM); var path = Server.MapPath ("/").            Replace ("\ \", "/");            var path = @ "C:\Users\Public\Documents\DevExpress Demos 18.1\components\asp.net\cs\aspxcardviewdemos"; htm = htm. Replace ("/content/", path+ "/content/"). Replace ("src=\", "src=\" "+path")//. Replace ("<script src=\", "<script src=\" "+ path")//. Replace ("type=\" text/css\ "href=\", "type=\" text/css\ "href=\" + path).            Replace ("//", "/");            Create the HTML to PDF converter htmltopdf htmltopdfconverter = new Htmltopdf ();            Set browser width htmltopdfconverter.browserwidth = 1440;            Set browser height if specified, otherwise use the default htmltopdfconverter.browserheight = height; Set HTML Load Timeout//htmltopdfconverter.htmlloadedtimeout = Int.            Parse (Textboxloadhtmltimeout.text); Set PDF page size and orientation//htmltopdfconverter.document.pagesize = new Pdfpagesize ((float) (WIDTH/2            .4), (float) (height/2.4));            HtmlToPdfConverter.Document.PageSize = new Pdfpagesize (htmltopdfconverter.browserwidth, height);            HtmlToPdfConverter.Document.PageOrientation = pdfpageorientation.portrait; Set the PDF standard used by the document HtmlToPdfConverter.Document.PdfStandard = PDFSTANDARD.PDF;//CHECKB Oxpdfa.checked?            PDFSTANDARD.PDFA://Set PDF page margins htmlToPdfConverter.Document.Margins = new Pdfmargins (0);            Set whether to embed the true Type font in PDF htmlToPdfConverter.Document.FontEmbedding = true; Set triggering mode;             For WaitTime mode set the wait time before convert htmltopdfconverter.triggermode = Conversiontriggermode.auto; // Set Header and Footer//setheader (htmltopdfconverter.document);            Setfooter (htmltopdfconverter.document);            Set the document security//htmltopdfconverter.document.security.openpassword = Textboxopenpassword.text;            HtmlToPdfConverter.Document.Security.AllowPrinting = true; Set the permissions password too if an open password is set if (htmlToPdfConverter.Document.Security.OpenPa ssWOrd! = NULL && HtmlToPdfConverter.Document.Security.OpenPassword! = String.Empty) htmltopdfconve Rter.            Document.Security.PermissionsPassword = HtmlToPdfConverter.Document.Security.OpenPassword + "_admin";            Cursor = Cursors.waitcursor;            Convert HTML to PDF string pdffile = null;            Convert URL to a PDF memory buffer//string URL = formcollection["Textboxurl"];            byte[] Pdfbuffer = htmltopdfconverter.converthtmltomemory (htm, null); //Send the PDF document to browser Fileresult Fileresult = new Filecontentresult (Pdfbuffer, "application/pdf");            Fileresult.filedownloadname = "Htmltopdf.pdf";        Return File (Pdfbuffer, "Application/octet-stream", "test.pdf"); }
      JS inside this activation (note the translation of HTML):
        var DownLoadFile = function (options) {var config = $.extend (True, {method: ' Post '}, options);            var $iframe = $ (' <iframe id= "down-file-iframe"/> ');            var $form = $ (' <form target= "down-file-iframe" method= "' + Config.method + '"/> ');            $form. attr (' action ', Config.url); for (var key in Config.data) {$form. Append (' <input type= "hidden" name= "' + key + '" value= "' + CONFIG.D            Ata[key] + '/> ');            } $iframe. Append ($form);            $ (document.body). Append ($iframe);            $form [0].submit ();        $iframe. Remove ();                 } DownLoadFile ({url: "Http://localhost:3095/test/getPDFfromHtmlCode",//the URI of your controller Data: {"height": $ ("body"). Outerheight (), "width": $ ("body"). Outerwidth (), "htm": Escape (Document.getelem Entsbytagname ("HTML") [0].innerhtml], "head": "Test"}//the data in your request, according to your controller            }); 

Final description

First of all the pages you want to transfer the best resource files are absolute path, because paddle, your server can not get the resource files to render, of course, do not give you a perfect PDF

Second, if it is a relative path, you need to use replace Dafa on the backend to turn the relative path to the absolute path that the server can obtain.

Second, the ultimate approach is to put the page inside the left and right resources files, you have to manually download to the server, and then the relative address are referenced to this location, in addition to the magic of the style, basically can do what you see is the income

The free version of the hiqpdf will be in the header location of the file, this time reflects the benefits of our approach: the exported PDF is not a picture but a real PDF code, so you can use Foxit and other software to open the watermark removed

(Of course you can also directly replace the code in the back end, I do not have, eye pain (๑´ڡ ' ๑))

Start a brain, in fact, with markdown, online Excel, online resume design and so on, you can easily get a good-looking PDF document, chart, CV ~ ~

So do not struggle with my code is good-looking, is the main idea-encounter mountain hewing, sea reclamation: The front end can not be very good rendering, then put to the back end; The back end can not get the relative path, turn to absolute path, manual trouble, package into post, with the codec function ""

You see, Html2canvas 2pdf have so much praise, the effect is actually a blurred picture, and we, with a simple low-level idea, got a nearly perfect PDF file, so, train of thought ah old iron ~ ~

Statement:

    • There is no intention to support piracy, we have the right to use Hiqpdf, trial free version of the law does not violate the effect or can be ~ ~
    • For non-developers or pure front-end, this method is still a little bit of cost, here apologize
    • Between the 2nd, I am ready to work a bit more secure after the establishment of an online site, the realization of ideas have been, I hope that there will be like-minded big guys to give advice, more help ~ ~

Now that you've seen it, move your mouse over to the top right corner and give it a star ( ¯³¯ ) ♡ㄘゅ

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.