在各种业务环境中,将各种文档合并为一个PDF是客户最常问的问题之一。例如,假设您的组织有多个应用程序以XPS和PDF生成特定的文档,使用扫描的图像,并且您的用户希望将其中一些文档合并为一个PDF。
本文演示了如何使用ASP.NET Core框架将多个文档合并到一个PDF中。Aspose.PDF提出了几种使用.NET合并PDF的方法,这些内容在本文中进行了介绍。在本文中,将讨论以下主题:
- 如何使用ASP.NET Core Web API上传PDF或其他文档;
- 如何实现简单的Web UI来选择要合并的PDF文件;
- 如何实现用于合并PDF的简单Web API容器;
在本文中,我们将创建一个简单的ASP.NET Web API应用程序,该应用程序允许我们上载文档,选择2个或更多文件进行合并以及下载结果。
实施ASP.NET Core Web App以将各种文档合并为PDF
步骤1:创建一个ASP.NET Core Web应用程序
我们将为此应用程序使用Web应用程序(模型-视图-控制器)模板。
创建基本应用程序后,我们将需要执行一些其他操作。
- 为.NET库添加Aspose.PDF作为依赖项(通过Nuget软件包管理器);
- 添加resumable.js库;
- 将临时文件和文档的wwwroot文件夹添加到该文件夹(例如files和temp);
- 在appsettings.json中创建相应的属性
"Folders": { "Files": "files", "Temporary" : "temp" }
步骤2:实施Web API控制器以管理服务器上的文件
我们的控制器应执行以下操作:
- 返回具有某些扩展名的文件列表(在本示例中,将仅显示.pdf,.jpg和.oxps文件);
- 允许按文件名下载文件;
- 允许通过文件名删除服务器上的文件;
using Aspose.Demo.Pdf.Merger.Models; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.Extensions.Configuration; namespace Aspose.Demo.Pdf.Merger.Controllers { [Route("api/[controller]")] [ApiController] public class FilesController : ControllerBase { private readonly Dictionary<string, string> _contentType; private readonly ILogger<FilesController> _logger; private readonly string _storageRootFolder; public FilesController(ILogger<FilesController> logger, IWebHostEnvironment env, IConfiguration configuration) { _logger = logger; _storageRootFolder = Path.Combine(env.WebRootPath, configuration["Folders:Files"]); _contentType = new Dictionary<string, string> { { ".txt", "text/plain"}, { ".pdf", "application/pdf"}, { ".doc", "application/vnd.ms-word"}, { ".docx", "application/vnd.ms-word"}, { ".xls", "application/vnd.ms-excel"}, { ".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}, { ".png", "image/png"}, { ".jpg", "image/jpeg"}, { ".jpeg", "image/jpeg"}, { ".gif", "image/gif"}, { ".csv", "text/csv"} }; } // GET: /api/files [HttpGet] public IEnumerable<FileVi