Phantomjs HTML to PDF

Source: Internet
Author: User
Tags httpcontext

Using system;using system.collections.generic;using system.linq;using system.web;using System.Configuration;using system.io;///<summary>///pdfcommon Summary description///</summary>public class Pdfcommon{public PDFCommon () {} public static string createpdf (string url) {string filenamewithoutextention = Guid.NewGuid ().        ToString ();        String path = System.Web.HttpContext.Current.Server.MapPath (@ "~\bin\phantomjs\");        string paths = System.Web.HttpContext.Current.Server.MapPath (@ "~\chartpdffile"); String savepath = Path.Combine (@ "d:/", String.        Format ("{0}.pdf", Guid.NewGuid ()));        String filePath = Path.Combine (Path, "Phantomjs.exe");        String jspath = Path.Combine (Path, "generate_pdf.js"); string argument = string.        Format ("--ignore-ssl-errors=yes {0} \" {1}\ "{2}", Jspath, URL, savepath); using (System.Diagnostics.Process Exep = new System.Diagnostics.Process ()) {System.Diagnostics.ProcessS Tartinfo startinfo = new SyStem.            Diagnostics.processstartinfo ();            Startinfo.filename = FilePath;            startinfo.arguments = argument;            Startinfo.createnowindow = true;            Startinfo.useshellexecute = false;            Startinfo.redirectstandardinput = true;            Startinfo.redirectstandardoutput = true;            Startinfo.redirectstandarderror = true; Exep.            StartInfo = StartInfo; Exep.            Start (); Exep.        WaitForExit ();    } return Savepath; }}

This file was not a browser-run JavaScript but phantonjs scriptvar system = require (' system '); var address = system.args[ 1];var output = System.args[2];var page = require (' webpage '). Create ();p age.papersize = {format: ' A4 ', Orientation: ' LAN Dscape ', border: ' 1cm '};p age.open (address, function (status) {if (Status!== ' success ') {Console.log (' unable        To load the address! ');    Phantom.exit ();             } else {window.settimeout (function () {//Remove all low-opacity paths. See PHANTOMJS issue #364                Page.evaluate (function () {var paths = document.getElementsByTagName ("path");                    for (var i = paths.length-1; I >= 0; i--) {var path = paths[i];                    var strokeopacity = Path.getattribute (' stroke-opacity ');                if (strokeopacity! = null && strokeopacity < 0.2) path.parentNode.removeChild (path);           }            }); Page.render (output);        Phantom.exit ();    }, 5000); }});

  

Opening

Recently, a PDF was generated using PHANTOMJS, which encountered some problems that caused the PDF build to fail, such as a blank file or a large amount of data on one page, due to the lack of formatting. In particular, the problem of paging, feeling very little information, in addition to see some information on the StackOverflow, the Chinese community basically do not see, with the revised rasterize.js to do the explanation:

var page = require (' webpage '). Create (),
System = require (' System '),
Address, output, size;

if (System.args.length < 3 | | system.args.length > 5) {
Console.log (' Usage:rasterize.js URL filename [paperwidth*paperheight|paperformat] [zoom] ');
Console.log (' paper (PDF output) Examples: "5in*7.5in", "10cm*20cm", "A4", "letter");
Phantom.exit (1);
} else {
address = system.args[1];
output = system.args[2];
/*size of browser*/
Page.viewportsize = {width:600, height:600};
/*
if (System.args.length > 3 && system.args[2].substr ( -4) = = = ". pdf") {
Size = System.args[3].split (' * ');
Page.papersize = Size.length = = = 2? {width:size[0], height:size[1], margin: ' 0px '}
: {format: ' A4 ', Orientation: ' Portrait ', margin: ' 1cm '};
}
*/
/* IE and chrome view diffrent format of PDF */
page.settings.userAgent = ' mozilla/5.0 applewebkit/537.36 (khtml, like Gecko) chrome/33.0.1750.117 safari/537.36 ';
page.papersize = {format: ' A4 ', Orientation: ' Portrait ', Margin: ' 0.8cm '};
Page.zoomfactor = 1;
Page.settings.loadImages = true;
Some question about the page language
Page.open (address, function (status) {
if (Status!== ' success ') {
Console.log (' Unable to load the address! ');
} else {
Page.render (output);
Phantom.exit ();

Window.settimeout (function () {
Page.render (output);
Phantom.exit ();
}, 200); Setting the time is enough to loading the page. Document.ready

}
});
}

 1 var page = require (' webpage '). Create (), 2 system = require (' System '), 3 address, output, size; 4 5 if (System.args.length < 3 | | system.args.length > 5) {6 Console.log (' Usage:rasterize.js URL filename [pa Perwidth*paperheight|paperformat] [zoom] '); 7 Console.log (' paper (PDF output) Examples: "5in*7.5in", "10cm*20cm", "A4", "letter"); 8 Phantom.exit (1); 9} else {address = system.args[1];11 output = system.args[2];12/*size of BROWSER*/13 Page.viewportsiz E = {width:600, height:600};14/*15 if (system.args.length > 3 && system.args[2].substr ( -4) = = = ". P DF ") {size = System.args[3].split (' * '); page.papersize = Size.length = = = 2? {width:size[0], height:size[1], margin: ' 0px '}18: {format: ' A4 ', Orientat Ion: ' Portrait ', margin: ' 1cm '};19}20 */21/* IE and chrome view diffrent format of PDF */22 Page.settin Gs.useragent = ' MOZILLA/5.0 applewebkit/537.36 (khtml, like Gecko) chrome/33.0.1750.117 safari/537.36 '; page.papersize = {format: ' A4 ', Orie Ntation: ' Portrait ', Margin: ' 0.8cm '};24 page.zoomfactor = 1;25 page.settings.loadImages = true;26//some que             Stion about the page Language27 page.open (address, function (status) {if (Status!== ' success ') {29 Console.log (' Unable to load the address! '); -else {//page.render (output),//phantom.exit (); Ow.settimeout (function () {page.render (output); Phantom.exit (); 37}, 200) ; Setting the time is enough to loading the page. DOCUMENT.READY38 39}40}); 41}

PDF format settings

Here you can learn more about the setting properties of page in the webpage Module.

The settings we need are basically page formatting, zooming, loading pictures, etc., but with some exceptions, the following one by one explains.

1 page.papersize = {format: ' A4 ', Orientation: ' Portrait ', Margin: ' 0.8cm '};

Commented out the official example of the setup code, because the incoming parameters only 3, to. pdf, if written as a common mode, of course, can be passed as an external parameter.

FORMAT:A4 paper, can be set "5in*7.5in", "10cm*20cm", "letter" and so on

Orientation: Paper direction is vertical, or landscape

Margin: With the width of the paper, customizable, can also be set in detail margin: {left: ' 0.8cm ', Top: ' 0.8cm ', right: ' 0.8cm ', bottom: ' 0.8cm '}

1 Page.zoomfactor = 1;2 Page.settings.loadImages = true;

Zoomfactor: Page Zoom ratio

Loadimages: Page load Picture

1 page.settings.userAgent = ' mozilla/5.0 applewebkit/537.36 (khtml, like Gecko) chrome/33.0.1750.117 safari/537.36 ';

This setting is less common and is not mentioned in the general example, because it is a bit different (in terms of paging) to open the generated PDF with chrome and IE, so set this value to resolve this inconsistency due to the preference for Chrome browsing format.

Page.open inside the SetTimeout method function: Wait for the page to finish JS, and then generate a PDF. Of course, how long the JS to be executed (how long to wait), this will not know how to budget. I actually tried the Ajax way to load the content, but the problem was dropped.

For more information, you can refer to the Header and footer and page number labeling questions here.

PDF Paging

Paging, better control, do not need code (JS) settings, page use style:

1 style = “page-break-afteralways;”

Control the size of content per page, using <div style= "page-break-after:always;" >content</div> on the line.

More Options style= "page-break-before:always;", style= "page-break-inside:avoid;" This avoids the content being scattered over two pages.

Phantomjs HTML to PDF

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.