使用 iTextSharp 将 PDF 文件转换为图片 - .NET Core 异步处理
要将 PDF 文件转换为图片,可以使用第三方库 iTextSharp。iTextSharp 是一个 .NET 库,可用于创建和处理 PDF 文档。以下是将 PDF 文件转换为图片的步骤:
- 将 PDF 文件上传到服务器。
- 使用 iTextSharp 库打开 PDF 文件。
- 使用 iTextSharp 库将 PDF 文件的每个页面转换为图片。
- 将每个生成的图片保存到服务器上的指定文件夹中。
以下是示例代码:
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
public async Task<IActionResult> UploadPDF(IFormFile file)
{
if (file == null || file.Length == 0)
{
return BadRequest('Could not upload file');
}
// Create a unique file name for the PDF file
string fileName = Guid.NewGuid().ToString() + '.pdf';
// Save the PDF file to the server
var filePath = Path.Combine(Directory.GetCurrentDirectory(), 'pdfs', fileName);
using (var stream = new FileStream(filePath, FileMode.Create))
{
await file.CopyToAsync(stream);
}
// Convert the PDF file to images
var imagePaths = ConvertPDFToImages(filePath);
// Return the image paths as JSON
return Ok(imagePaths);
}
private List<string> ConvertPDFToImages(string filePath)
{
List<string> imagePaths = new List<string>();
// Open the PDF file
using (var reader = new PdfReader(filePath))
{
// Get the number of pages in the PDF file
int numPages = reader.NumberOfPages;
// Loop through each page in the PDF file
for (int i = 1; i <= numPages; i++)
{
// Get the current page as an image
var page = reader.GetPageN(i);
var size = page.PageSize;
var render = new PdfRenderer(page, size.Width, size.Height, true, true);
var image = render.RenderImage();
// Save the image to a file
string imageName = Path.GetFileNameWithoutExtension(filePath) + '_page' + i + '.png';
string imagePath = Path.Combine(Directory.GetCurrentDirectory(), 'images', imageName);
using (var stream = new FileStream(imagePath, FileMode.Create))
{
image.Save(stream, ImageFormat.Png);
}
// Add the image path to the list
imagePaths.Add(imagePath);
}
}
return imagePaths;
}
此代码将 PDF 文件上传到服务器,然后将其转换为 PNG 图像。将生成的图像保存到指定文件夹中,并将图像路径返回给调用者。请注意,此代码中的文件路径都是硬编码的,应该根据实际需要进行更改。
原文地址: https://www.cveoy.top/t/topic/okwR 著作权归作者所有。请勿转载和采集!