C# 生成的 PDF 文件无法在 PDF 阅读器中打开。错误显示损坏或损坏的文件



我试图将imageData保存为服务器目录上的pdf文件。Html5Canvas imageData被发送到服务器,转换成字节数组后,试图保存为PDF文件。文件在指定路径上生成成功,但生成的文件在大多数PDF阅读器中不能正确打开(即:Adobe Reader, Foxit Reader等),并显示文件损坏或损坏的错误,但它在MS Edge浏览器中正确打开。我希望它们也能显示在普通的PDF阅读器中。你能提出解决方案吗?这是我的服务器端代码。

public static string SaveImage(string imageData, string userEmail, int quantity)
    {
        string completePath = @"~user-images";
        string imageName = "sample_file2.pdf";
        string fileNameWitPath = completePath + imageName;
        byte[] bytes = Convert.FromBase64String(imageData);
        File.WriteAllBytes(HttpContext.Current.Server.MapPath(fileNameWitPath), bytes);
    }

与此代码生成的输出相同

        FileStream fs = new FileStream(HttpContext.Current.Server.MapPath(fileNameWitPath), FileMode.OpenOrCreate);
        fs.Write(bytes, 0, bytes.Length);
        fs.Close();

 using (FileStream fs = new FileStream(HttpContext.Current.Server.MapPath(fileNameWitPath), FileMode.Create))
        {
            using (BinaryWriter bw = new BinaryWriter(fs))
            {
                byte[] data = Convert.FromBase64String(imageData);
                bw.Write(data);
                bw.Close();
            }
        }

如果您只是保存栅格图像格式文件(如PNG或JPG)与.PDF文件扩展名,它不会使其成为PDF文件;它仍然是一个具有另一个扩展名的图像文件。因此,它可能在某些浏览器中工作,因为它们可能会进行文件格式检测,而不是仅基于扩展名。

要生成一个实际的PDF文件,您将需要使用一些转换。考虑以下库之一:

  • iTextSharp: https://sourceforge.net/projects/itextsharp/(AGPL =一个允许非商业用途的免费软件许可证。商业使用需要购买商业许可)
  • PDFSharp http://www.pdfsharp.net/(免费,MIT许可)
  • ABCpdf。. NET http://www.websupergoo.com/products.htm#abcpdf(专有)

最新更新