C#代码:将Word文档转换为PDF格式
这段代码的功能是将上传的Word文档转换为PDF格式并保存到指定位置。 代码中首先判断文件是否为Word文档,若不是则直接返回。 然后获取原文件路径和新文件路径,将原文件读入'XWPFDocument'对象中,创建PDF文档对象、PDF写入器对象和PDF段落对象,遍历原文档的所有段落,将每个段落的文本内容加入PDF段落对象中,最后将PDF文档保存到指定路径。 这段代码需要检查一下是否存在异常处理和资源释放的问题。
bool word = uploadModel.FormFile.FileName.EndsWith('.docx') || uploadModel.FormFile.FileName.EndsWith('.doc');
if (!word)
return;
string oldPath = Path.Combine(uploadModel.RootPath, uploadModel.Module, uploadModel.Group, result.Data.FullPath);
string newDirPath = GeneratePath(uploadModel.FullPath, 'wordtopdf');
result.Data.SaveName = result.Data.SaveName.Replace($'.{result.Data.Ext}', '.pdf');
string newPath = Path.Combine(uploadModel.FullPath, newDirPath, result.Data.SaveName);
using var fileStream = new FileStream(oldPath, FileMode.Open, FileAccess.Read);
var document = new XWPFDocument(fileStream);
using var pdfStream = new FileStream(newPath, FileMode.Create, FileAccess.Write);
var pdfDocument = new iTextSharp.text.Document();
var pdfWriter = PdfWriter.GetInstance(pdfDocument, pdfStream);
pdfDocument.Open();
foreach (var paragraph in document.Paragraphs)
{
var pdfParagraph = new Paragraph(paragraph.ParagraphText, FontFactory.GetFont(FontFactory.HELVETICA, 12));
pdfDocument.Add(pdfParagraph);
}
pdfDocument.Close();
原文地址: https://www.cveoy.top/t/topic/oomi 著作权归作者所有。请勿转载和采集!