在本分步主题中,您将学习如何在 C# 中将 PUB 转换为 PNG。当您需要在应用程序中将 PUB 文件的页面显示为图像时,需要在 C# 中将 PUB 文件转换为 PNG 格式。本教程通过几行 C# 代码帮助您实现这一目标。
在 C# 中将 PUB 转换为 PNG 的步骤
- 从 NuGet.org 安装 Aspose.PUB for .NET 和 Aspose.PDF for .NET 包
- 引用四个必需的命名空间以使代码工作
- 使用 SetLicense 方法分别为两个 API 设置许可证
- 使用 PubFactory class 为 PUB 文件创建解析器
- 将解析后的 PUB 文件加载到 Document object
- 使用 IPdfConverter interface 保存中间 PDF 文件
- 创建一个新的 PDF Document object
- 循环浏览 PDF 文件的所有页面
- 使用 PngDevice object 将每个 PDF 页面保存为 PNG 图像
在上述步骤中,我们使用了 Aspose.PUB for .NET 和 Aspose.PDF for .NET API,首先将 PUB 文件转换为中间 PDF 文件格式,然后将该中间 PDF 文件转换为 PNG 图像。
在 C# 中将 PUB 转换为 PNG 的代码
using System; | |
//Add reference to Aspose.PUB for .NET API | |
//Use following namespaces to convert PUB to PNG image format | |
using Aspose.Pub; | |
using PDF = Aspose.Pdf; | |
using Aspose.Pdf.Facades; | |
using Aspose.Pdf.Devices; | |
namespace ConvertPUBToPNG | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
//Set Aspose license before converting PUB to PNG format | |
//using Aspose.PUB for .NET | |
Aspose.Pub.License AsposePUBLicense = new Aspose.Pub.License(); | |
AsposePUBLicense.SetLicense(@"c:\asposelicense\license.lic"); | |
Aspose.Pdf.License AsposePDFLicense = new Aspose.Pdf.License(); | |
AsposePDFLicense.SetLicense(@"c:\asposelicense\license.lic"); | |
//Load a parsed version of Pub file to Document object | |
IPubParser PubFileParser = PubFactory.CreateParser("InputPUBFileToConvert.pub"); | |
Document PubDocument = PubFileParser.Parse(); | |
//convert to PDF using PDFConvert object | |
IPdfConverter PDFConverter = PubFactory.CreatePdfConverter(); | |
PDFConverter.ConvertToPdf(PubDocument, "IntermediatePDFFile.pdf"); | |
//create a PDF document | |
PDF.Document PDFDocument = new PDF.Document("IntermediatePDFFile.pdf"); | |
PdfFileInfo PDFFileInfo = new PdfFileInfo(PDFDocument); | |
//loop through each page and save it as PNG | |
foreach (PDF.Page PDFPage in PDFDocument.Pages) | |
{ | |
PDF.PageSize PDFPageSize = new PDF.PageSize( | |
Convert.ToInt32(PDFFileInfo.GetPageWidth(PDFPage.Number)), | |
Convert.ToInt32(PDFFileInfo.GetPageHeight(PDFPage.Number))); | |
PDF.Devices.PngDevice PNGDevice = new PDF.Devices.PngDevice(PDFPageSize); | |
PNGDevice.Process(PDFPage, "Page" + PDFPage.Number + ".png"); | |
} | |
} | |
} | |
} |
上面的代码通过几个步骤在 C# 代码中帮助 convert PUB 转换为 PNG。 PDF 文件的每个单独页面都保存为单独的 PNG 图像。使用此代码并按照步骤操作,您可以在 .NET 应用程序(包括 Windows、Web、桌面或服务等)中创建自己的 PUB 到 PNG C# 转换器。请注意,这不需要在您的计算机或服务器上安装 Microsoft Publisher .