C # generates PDFs based on HTML

Source: Internet
Author: User
Tags httpcontext string back

Http://www.cnblogs.com/kongxiaoshuang/p/6347565.html

http://blog.csdn.net/zhang116868/article/details/44879401

Using the Itextsharp control

Using System;
Using System.Collections.Generic;

Using System.Web;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Using Itextsharp.text;
Using ITextSharp.text.pdf;
Using System.IO;
Using ITextSharp.tool.xml;
Using System.Text;
Using System.Net;

Namespace Pdftools
{
public partial class CreatePdf:System.Web.UI.Page
{
String inpath = System.Web.HttpContext.Current.Server.MapPath ("~/bin/temp.html");

protected void Page_Load (object sender, EventArgs e)
{
String path = System.Web.HttpContext.Current.Server.MapPath ("~/uploadpdf");
if (! Directory.Exists (PATH))
Directory.CreateDirectory (path);

WebClient WC = new WebClient ();
Download the HTML string from the URL
Wc. Encoding = System.Text.Encoding.UTF8;
String htmltext = Getwebcontent ();
Byte[] Pdffile = this. Converthtmltexttopdf (HTMLText);

String fileId = "/file_" + DateTime.Now.ToString ("YYYYMMDDHHMMSS") + ". pdf";
System.IO.File.WriteAllBytes (path + fileId, pdffile);
}

<summary>
Determine if there are garbled characters
</summary>
<param name= "TXT" ></param>
<returns></returns>
public bool Ismessycode (string txt)
{
var bytes = Encoding.UTF8.GetBytes (TXT); 239 191 189
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>
Get the content of the website, including HTML+CSS+JS
</summary>
<returns>string back to Web information </returns>
public string getwebcontent ()
{
Try
{
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>
Output HTML text to a PDF file
</summary>
<param name= "HTMLText" ></param>
<returns></returns>
Public 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 ();//To write a PDF file, the constructor is not filled with the pre-set straight A4
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 ();

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
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 marked in italics Path = Path.Combine (Environment.getfolderpath (Environment.SpecialFolder.Fonts),
"Kaiu. TTF ");//mark in italics


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\SIMSUN. ttc,1 ", Basefont.identity_h, basefont.not_embedded);
Use Arial or italic, choose one of your own
Basefont Basefont = Basefont.createfont (marked in italics path, basefont.identity_h, basefont.embedded);
return new Font (bfchiness, size, style, color);
}
}
}
}

C # generates PDFs based on HTML

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.