0

我正在尝试使用 PDFsharp 从 PDF 文件中提取图像。我运行代码的测试文件显示过滤器类型为 /JBIG2。如果可以使用 PDFSharp,我希望帮助了解如何解码并保存此图像。

我用来提取图像然后保存的代码如下:

const string filename = "../../../test.pdf";            
PdfDocument document = PdfReader.Open(filename);
int imageCount = 0;

foreach (PdfPage page in document.Pages) { // Iterate pages
  // Get resources dictionary
  PdfDictionary resources = page.Elements.GetDictionary("/Resources");

  if (resources != null) {
    // Get external objects dictionary
    PdfDictionary xObjects = resources.Elements.GetDictionary("/XObject");

    if (xObjects != null) {
      ICollection<PdfItem> items = xObjects.Elements.Values;

      foreach (PdfItem item in items) { // Iterate references to external objects
        PdfReference reference = item as PdfReference;

        if (reference != null) {
          PdfDictionary xObject = reference.Value as PdfDictionary;

          // Is external object an image?
          if (xObject != null && xObject.Elements.GetString("/Subtype") == "/Image") {
            ExportImage(xObject, ref imageCount);
          }
        }
      }
    }
  }
}

static void ExportImage(PdfDictionary image, ref int count) {
   string filter = image.Elements.GetName("/Filter");

   switch (filter) {
     case "/DCTDecode":
       ExportJpegImage(image, ref count);
       break;
     case "/FlateDecode":
       ExportAsPngImage(image, ref count);
       break;
   }  
}

static void ExportJpegImage(PdfDictionary image, ref int count) {
  // Fortunately, JPEG has native support in PDF and exporting an image is just writing the stream to a file.
  byte[] stream = image.Stream.Value;
  FileStream fs = new FileStream(
    String.Format("Image{0}.jpeg", count++), FileMode.Create, FileAccess.Write
  );
  BinaryWriter bw = new BinaryWriter(fs);
  bw.Write(stream);
  bw.Close();
}

在上面,我得到的过滤器类型为/JBIG2,我确实支持。上面的代码来自PDFSharp: Export Images Sample

4

1 回答 1

-1

JBIG2 在 PDF 中使用最广泛,但在 PDF 之外则是另一回事。尽管 .jbig2 是一种光栅图像格式,但就图像查看器而言,对它的支持非常少。您最好的办法是像 Acrobat 一样将其导出为 CCITT4 压缩 TIFF。

于 2019-03-30T07:28:21.373 回答