Generate PDF files from HTML files

Source: Internet
Author: User
Tags string back

<summary>
Get HTML content and turn it into PDF (register)

</summary>
public void downloadpdfbyhtml (String html,string FileName)
{


WebClient WC = new WebClient ();
//
Wc. Encoding = System.Text.Encoding.UTF8;
String htmltext = Getwebcontent ();
String htmltext = Html;//getwebcontent ();

string dataname = filename;//Download file name

Byte[] Pdffile =converthtmltexttopdf (htmltext);

If you need to save to the server
String fileId = "/file_" + DateTime.Now.ToString ("YYYYMMDDHHMMSS") + ". pdf";
System.IO.File.WriteAllBytes (path + fileId, pdffile);
Response.ContentType = "Application/octet-stream";
Notifies the browser to download files
Response.AddHeader ("Content-disposition", "attachment; Filename= "+ httputility.urlencode (Dataname +". pdf ", System.Text.Encoding.UTF8));
Response.BinaryWrite (pdffile);//file Download binary stream
Response.Flush ();
Response.End ();
Delete the server file, notify after the download is successful, delete
FileInfo fi = new FileInfo (path + fileId);
if (FI. Exists)
//{
Fi. Delete ();
//}
}

<summary>
Get the content of the website, including HTML+CSS+JS
</summary>
<returns>string back to Web information </returns>
public string getwebcontent ()
{
Try
{
String inpath = System.Web.HttpContext.Current.Server.MapPath ("~/emailtemplet/sa.html");
WebClient mywebclient = new WebClient ();
Mywebclient.credentials = CredentialCache.DefaultCredentials;
Gets or sets the network credentials that are used to authenticate requests to Internet resources
byte[] Pagedata = Mywebclient.downloaddata (Inpath);
Download data from a specified Web site
String pagehtml = Encoding.UTF8.GetString (pagedata);
If you are using GB2312 to get a website page, use this sentence
BOOL Isbool =ismessycode (pagehtml);//determine which encoding to use to read Web page information
if (!isbool)
{
String pageHtml1 = Encoding.UTF8.GetString (pagedata);
pagehtml = PAGEHTML1;
}
Else
{
String pageHtml2 = Encoding.Default.GetString (pagedata);
pagehtml = PAGEHTML2;
}
return pagehtml;
}

catch (WebException webEx)
{
Console.WriteLine (WebEx.Message.ToString ());
return webex.message;
}
}


<summary>
Determine if there are garbled characters
</summary>
<param name= "TXT" ></param>
<returns></returns>
public static bool Ismessycode (String txt)
{
var bytes = Encoding.UTF8.GetBytes (TXT);
for (var i = 0; i < bytes. Length; i++)
{
if (I < bytes. Length-3)
if (bytes[i] = = 239 && bytes[i + 1] = = 191 && bytes[i + 2] = = 189)
{
return true;
}
}
return false;
}




<summary>
Output HTML text to a PDF file
</summary>
<param name= "HTMLText" ></param>
<returns></returns>
public static byte[] Converthtmltexttopdf (string htmltext)
{
if (string. IsNullOrEmpty (HTMLText))
{
return null;
}
Avoid htmltext when the text is not in any HTML tag tag, when you go to PDF, it hangs, so add <p> tag
HTMLText = "<p>" + htmltext + "</p>";

MemoryStream outputstream = new MemoryStream ();//to which stream to write the PDF
byte[] data = Encoding.UTF8.GetBytes (htmltext);//string turns into byte[]
MemoryStream msinput = new MemoryStream (data);
Document doc = new document (PageSize.A4.Rotate (), 1, 1, 1, 1);//To write a PDF file, the constructor is not filled with the preset straight A4 (the value is not filled in parentheses by default is A4 portrait, otherwise landscape)

PDFWriter writer = pdfwriter.getinstance (doc, OutputStream);
Specifies that the file preset is scaled to 100% when it is opened

Pdfdestination pdfdest = new Pdfdestination (pdfdestination.xyz, 0, Doc. Pagesize.height, 1f);
Open Document File
Doc. Open ();
Doc. ADD (ITextSharp.text.PageSize.A5.Rotate ());
Use Xmlworkerhelper to parse HTML into PDF file
Xmlworkerhelper.getinstance (). Parsexhtml (writer, doc, msinput, NULL, Encoding.UTF8, New Unicodefontfactory ());
Xmlworkerhelper.getinstance (). Parsexhtml (writer, doc, msinput, NULL, ENCODING.UTF8);

Write the pdfdest data to a PDF file
Pdfaction action = pdfaction.gotolocalpage (1, pdfdest, writer);
Writer. Setopenaction (action);
Doc. Close ();
Msinput.close ();
Outputstream.close ();
return PDF file
return Outputstream.toarray ();

}

Set the Font class (only English is displayed if there is a problem with the font setting)
public class Unicodefontfactory:fontfactoryimp
{
private static readonly String Arialfontpath = Path.Combine (Environment.getfolderpath ( Environment.SpecialFolder.Fonts),
"Arialuni.ttf");//arial Unicode MS is the complete Unicode font.
private static readonly String Fonttypepath = Path.Combine (Environment.getfolderpath (Environment.SpecialFolder.Fonts ),
"Stkaiti. TTF ");


public override Font GetFont (string fontname, string encoding, bool embedded, float size, int style, basecolor color, bool Cached
{
Basefont bfchiness = Basefont.createfont (@ "C:\\windows\\fonts\\stkaiti. TTF ", Basefont.identity_h, basefont.not_embedded);
Use Arial or italic, choose one of your own
Basefont Basefont = Basefont.createfont (Fonttypepath, Basefont.identity_h, basefont.embedded);
return new Font (bfchiness, size, style, color);
}
}

Reprint to: https://www.cnblogs.com/zhurunlai/p/7193201.html

Generate PDF files from HTML files

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.