Aspose.PDF for .NET(點擊下載)是一種高級PDF處理和解析API,用於在跨平臺應用程序中執行文檔管理和操做任務。API能夠輕鬆用於生成,修改,轉換,渲染,保護和打印PDF文檔,而無需使用Adobe Acrobat。此外,還提供PDF壓縮選項,表格建立和操做,圖形和圖像功能,普遍的超連接功能,印章和水印任務,擴展的安全控制和自定義字體處理。html
HTML到PDF的轉換在將不一樣文件格式相互轉換之間具備其自身的意義,可使用其餘可用的應用程序,工具和在線服務將HTML轉換爲PDF。一樣,咱們也可使用編程的方式,將HTML轉換爲PDF。編程
在Aspose.PDF for .Net中,提供了免費的HTML到PDF的基本轉換,並且還容許指定各類選項來實現所需的功能,好比將網頁轉換爲PDF、使用SVG數據渲染HTML等等。接下來咱們一塊兒經過示例解讀的方式學習如何實現這些功能。安全
只需使用幾行代碼和資源加載回調就能夠以很是基本的方式將HTML轉換爲PDF,如下是使您達到目的的代碼段:服務器
// The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_DocumentConversion(); HtmlLoadOptions options = new HtmlLoadOptions(); options.CustomLoaderOfExternalResources = new LoadOptions.ResourceLoadingStrategy(SamePictureLoader); Document pdfDocument = new Document(dataDir + "HTMLToPDF.html", options); pdfDocument.Save("HTMLToPDF_out.pdf");
private static LoadOptions.ResourceLoadingResult SamePictureLoader(string resourceURI) { string dataDir = RunExamples.GetDataDir_AsposePdf_DocumentConversion(); byte[] resultBytes = File.ReadAllBytes(dataDir + "aspose-logo.jpg"); LoadOptions.ResourceLoadingResult result = new LoadOptions.ResourceLoadingResult(resultBytes); return result; }
一般須要將網頁轉換爲PDF,而且若是手動執行此操做,則須要執行多個步驟。API提供的功能可使用下面顯示的代碼執行。須要注意的是,如下代碼段涵蓋了Web頁面到PDF轉換操做的兩個主要和基本方面:工具
//文檔目錄的路徑。 string dataDir = RunExamples.GetDataDir_AsposePdf_DocumentConversion(); //建立對該URL的請求。 WebRequest request = WebRequest.Create("https:// En.wikipedia.org/wiki/Main_Page"); //若是服務器須要,請設置憑據。 request.Credentials = CredentialCache.DefaultCredentials; //在請求超時以前以毫秒爲單位超時 // Request.Timeout = 100; //獲取響應。 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); //獲取包含服務器返回內容的流。 Stream dataStream = response.GetResponseStream(); //使用StreamReader打開流以方便訪問。 StreamReader reader = new StreamReader(dataStream); //閱讀內容。 string responseFromServer = reader.ReadToEnd(); reader.Close(); dataStream.Close(); response.Close(); MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(responseFromServer)); HtmlLoadOptions options = new HtmlLoadOptions("https:// En.wikipedia.org/wiki/"); //加載HTML文件 Document pdfDocument = new Document(stream, options); options.PageInfo.IsLandscape = true; //將輸出另存爲PDF格式 pdfDocument.Save(dataDir + "WebPageToPDF_out.pdf");
如下代碼段顯示瞭如何將帶有SVG圖形標籤的HTML文件轉換爲Tagged PDF Document:學習
//文檔目錄的路徑 string dataDir = RunExamples.GetDataDir_AsposePdf_DocumentConversion(); //設置輸入文件路徑 string inFile = dataDir + "HTMLSVG.html"; //設置輸出文件路徑 string outFile = dataDir + "RenderHTMLwithSVGData.pdf"; //初始化HtmlLoadOptions HtmlLoadOptions options = new HtmlLoadOptions(Path.GetDirectoryName(inFile)); //初始化Document對象 Document pdfDocument = new Document(inFile, options); //保存 pdfDocument.Save(outFile);