通過html檔案產生PDF檔案

來源:互聯網
上載者:User

標籤:cache   head   bsp   www.   完整   二進位流   readonly   ++   cli   

/// <summary>
/// 擷取html內容,轉成PDF(註冊)

/// </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;//下載檔案名稱

byte[] pdfFile =ConvertHtmlTextToPDF(htmlText);

//如果需要儲存到伺服器
//string fileId = "/file_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".pdf";
//System.IO.File.WriteAllBytes(path + fileId, pdfFile);
Response.ContentType = "application/octet-stream";
//通知瀏覽器下載檔案
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(DataName + ".pdf", System.Text.Encoding.UTF8));
Response.BinaryWrite(pdfFile);//檔案下載二進位流
Response.Flush();
Response.End();
////刪除伺服器檔案,通知下載成功之後,刪除
//FileInfo fi = new FileInfo(path + fileId);
//if (fi.Exists)
//{
// fi.Delete();
//}
}

/// <summary>
/// 擷取網站內容,包含了 HTML+CSS+JS
/// </summary>
/// <returns>String返回網頁資訊</returns>
public string getWebContent()
{
try
{
string INPATH = System.Web.HttpContext.Current.Server.MapPath("~/EmailTemplet/sa.html");
WebClient MyWebClient = new WebClient();
MyWebClient.Credentials = CredentialCache.DefaultCredentials;
//擷取或設定用於向Internet資源的請求進行身分識別驗證的網路憑據
Byte[] pageData = MyWebClient.DownloadData(INPATH);
//從指定網站下載資料
string pageHtml = Encoding.UTF8.GetString(pageData);
//如果擷取網站頁面採用的是GB2312,則使用這句
bool isBool =isMessyCode(pageHtml);//判斷使用哪種編碼 讀取網頁資訊
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>
/// 判斷是否有亂碼
/// </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>
/// 將Html文字 輸出到PDF檔裡
/// </summary>
/// <param name="htmlText"></param>
/// <returns></returns>
public static byte[] ConvertHtmlTextToPDF(string htmlText)
{
if (string.IsNullOrEmpty(htmlText))
{
return null;
}
//避免當htmlText無任何html tag標籤的純文字時,轉PDF時會掛掉,所以一律加上<p>標籤
//htmlText = "<p>" + htmlText + "</p>";

MemoryStream outputStream = new MemoryStream();//要把PDF寫到哪個串流
byte[] data = Encoding.UTF8.GetBytes(htmlText);//字串轉成byte[]
MemoryStream msInput = new MemoryStream(data);
Document doc = new Document(PageSize.A4.Rotate(), 1, 1, 1, 1);//要寫PDF的檔案,建構子沒填的話預設直式A4(括弧內不填寫值預設是A4縱向,否則是橫向)

PdfWriter writer = PdfWriter.GetInstance(doc, outputStream);
//指定檔案預設開檔時的縮放為100%

PdfDestination pdfDest = new PdfDestination(PdfDestination.XYZ, 0, doc.PageSize.Height, 1f);
//開啟Document檔案
doc.Open();
doc.Add(iTextSharp.text.PageSize.A5.Rotate());
//使用XMLWorkerHelper把Html parse到PDF檔裡
XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msInput, null, Encoding.UTF8, new UnicodeFontFactory());
//XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msInput, null, Encoding.UTF8);

//將pdfDest設定的資料寫到PDF檔
PdfAction action = PdfAction.GotoLocalPage(1, pdfDest, writer);
writer.SetOpenAction(action);
doc.Close();
msInput.Close();
outputStream.Close();
//回傳PDF檔案
return outputStream.ToArray();

}

//設定字型類 (如果字型設定有問題,只能顯示英文)
public class UnicodeFontFactory : FontFactoryImp
{
private static readonly string arialFontPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts),
"arialuni.ttf");//arial unicode MS是完整的unicode字型。
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);
//可用Arial或標楷體,自己選一個
BaseFont baseFont = BaseFont.CreateFont(FontTypePath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
return new Font(bfChiness, size, style, color);
}
}

轉載至:https://www.cnblogs.com/zhurunlai/p/7193201.html

 

通過html檔案產生PDF檔案

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.