你在找HTML转换到PDF的方法吗?这篇Aspose.PDF for .NET教程告诉你!

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

只需使用几行代码和资源加载回调就能够以很是基本的方式将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

一般须要将网页转换为PDF,而且若是手动执行此操做,则须要执行多个步骤。API提供的功能可使用下面显示的代码执行。须要注意的是,如下代码段涵盖了Web页面到PDF转换操做的两个主要和基本方面:工具

  • 下载网页正在使用的资源,例如 CSS、图片
  • 提供凭据以防访问页面
//文档目录的路径。
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

如下代码段显示了如何将带有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);
相关文章
相关标签/搜索