英文:
convert PDF to image but PDF file path not found
问题
我正在尝试使用第三方工具IronPdf在ASP.NET中使用C#语言将PDF文件转换为图像。当我提交表单时,它显示以下错误。
C:\Program Files\IIS Express\Invoice-63457.pdf 不是有效的PDF文件路径。该文件不存在。
我的代码如下所示:
视图部分:
<form action="@Url.Action("ConvertPDF","Home")" method="post" enctype="multipart/form-data">
<input type="file" id="postedFile" name="postedFile" multiple="multiple" />
<br /><br /><br />
<p>
<input type="submit" value="Upload Files" class="btn btn-lg btn-primary" />
</p>
</form>
控制器部分:
[HttpPost]
public ActionResult ConvertPDF(HttpPostedFileBase postedFile)
{
var pdf = PdfDocument.FromFile(postedFile.FileName);
// 提取所有页面为图像文件到文件夹
pdf.RasterizeToImageFiles(@"C:\image\folder\*.png");
// 提取所有页面为AnyBitmap对象
AnyBitmap[] pdfBitmaps = pdf.ToBitmap();
return RedirectToAction("Index");
}
如何解决这个问题?
英文:
I am trying to convert PDF file into image using third party tool IronPdf in ASP.NET using C# language. When I submit the form, it show the following error.
C:\Program Files\IIS Express\Invoice-63457.pdf is not a valid PDF file path. That file does not exist.
My code is given below here
View Part
<form action="@Url.Action("ConvertPDF","Home")" method="post" enctype="multipart/form-data">
<input type="file" id="postedFile" name="postedFile" multiple="multiple" />
<br /><br /><br />
<p>
<input type="submit" value="Upload Files" class="btn btn-lg btn-primary" />
</p>
</form>
Controller Part:
[HttpPost]
public ActionResult ConvertPDF(HttpPostedFileBase postedFile)
{
var pdf = PdfDocument.FromFile(postedFile.FileName);
// Extract all pages to a folder as image files
pdf.RasterizeToImageFiles(@"C:\image\folder\*.png");
// Extract all pages as AnyBitmap objects
AnyBitmap[] pdfBitmaps = pdf.ToBitmap();
return RedirectToAction("Index");
}
How to solve it?
答案1
得分: 2
原因
出现这个问题的原因是您尝试以错误的方式加载文件。您必须使用从Stream
或Byte[]
创建PdfDocument
实例,因为当上传文件并在您的操作中接收该文件时,文件仅存在于Memory
中。根据文档,您可以像下面这样创建PdfDocument
实例。
public PdfDocument(byte[] PdfData, string Password = "")
或者
public PdfDocument(Stream PdfDataStream, string Password = "")
文档链接
https://ironpdf.com/object-reference/api/IronPdf.PdfDocument.html#constructors
解决方法
您必须将此部分替换为
var pdf = new PdfDocument(postedFile.InputStream);
英文:
Reason
The reason for this problem is you trying to load the file in the wrong way. You must use create PdfDocument
instance from Stream
or Byte[]
because when a file upload and you receive that file in your action, the file only exists on Memory
. according to document, you can create PdfDocument
instance like below.
public PdfDocument(byte[] PdfData, string Password = "", string OwnerPassword = "")
or
public PdfDocument(Stream PdfDataStream, string Password = "", string OwnerPassword = "")
document link
https://ironpdf.com/object-reference/api/IronPdf.PdfDocument.html#constructors
Soultion
You must replace this section
var pdf = PdfDocument.FromFile(postedFile.FileName);
with this
var pdf = new PdfDocument(postedFile.InputStream);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论