从 pdfsharp 中提取的旋转图像

发布于 2024-12-17 20:20:30 字数 543 浏览 2 评论 0 原文

我成功地使用 pdfsharp 从 pdf 中提取图像。图像是 CCITFFaxDecode。但在创建的 tiff 图像中,图像正在旋转。知道可能出了什么问题吗?

这是我使用的代码:

byte[] data = xObject.Stream.Value;
Tiff tiff = BitMiracle.LibTiff.Classic.Tiff.Open("D:\\clip_TIFF.tif", "w");
tiff.SetField(TiffTag.IMAGEWIDTH, (uint)(width));
tiff.SetField(TiffTag.IMAGELENGTH, (uint)(height));
tiff.SetField(TiffTag.COMPRESSION, (uint)BitMiracle.LibTiff.Classic.Compression.CCITTFAX4);
tiff.SetField(TiffTag.BITSPERSAMPLE, (uint)(bpp));
tiff.WriteRawStrip(0,data,data.Length);
tiff.Close();

I am successfully able to extract images from a pdf using pdfsharp. The image are of CCITFFaxDecode. But in the tiff image created , the image is getting rotated. Any idea what might be going wrong?

This is the code im using :

byte[] data = xObject.Stream.Value;
Tiff tiff = BitMiracle.LibTiff.Classic.Tiff.Open("D:\\clip_TIFF.tif", "w");
tiff.SetField(TiffTag.IMAGEWIDTH, (uint)(width));
tiff.SetField(TiffTag.IMAGELENGTH, (uint)(height));
tiff.SetField(TiffTag.COMPRESSION, (uint)BitMiracle.LibTiff.Classic.Compression.CCITTFAX4);
tiff.SetField(TiffTag.BITSPERSAMPLE, (uint)(bpp));
tiff.WriteRawStrip(0,data,data.Length);
tiff.Close();

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

星星的軌跡 2024-12-24 20:20:30

由于问题仍然被标记为 w/iTextSharp ,因此可能会添加一些代码,即使您看起来没有在这里使用该库。从 iText[Sharp] 5 开始添加了 PDF 解析支持。

没有包含您正在使用的图像类型的测试 PDF,但是 在这里找到了一个(见附件)。下面是 ASP.NETHTTP 处理程序 .ashx)中的一个非常简单工作示例,使用该测试 PDF 文档来让您继续:

<%@ WebHandler Language="C#" Class="CCITTFaxDecodeExtract" %>
using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
using Dotnet = System.Drawing.Image;
using System.Drawing.Imaging;

public class CCITTFaxDecodeExtract : IHttpHandler {
  public void ProcessRequest (HttpContext context) {
    HttpServerUtility Server = context.Server;
    HttpResponse Response = context.Response;
    string file = Server.MapPath("~/app_data/CCITTFaxDecode.pdf");
    PdfReader reader = new PdfReader(file);
    PdfReaderContentParser parser = new PdfReaderContentParser(reader);
    MyImageRenderListener listener = new MyImageRenderListener();
    for (int i = 1; i <= reader.NumberOfPages; i++) {
      parser.ProcessContent(i, listener);
    } 
    for (int i = 0; i < listener.Images.Count; ++i) {
      string path = Server.MapPath("~/app_data/" + listener.ImageNames[i]);
      using (FileStream fs = new FileStream(
        path, FileMode.Create, FileAccess.Write
      ))
      {
        fs.Write(listener.Images[i], 0, listener.Images[i].Length);
      }
    }         
  }
  public bool IsReusable { get { return false; } }
/*
 * see: TextRenderInfo & RenderListener classes here:
 * http://api.itextpdf.com/itext/
 * 
 * and Google "itextsharp extract images"
 */
  public class MyImageRenderListener : IRenderListener {
    public void RenderText(TextRenderInfo renderInfo) { }
    public void BeginTextBlock() { }
    public void EndTextBlock() { }

    public List<byte[]> Images = new List<byte[]>();
    public List<string> ImageNames = new List<string>();
    public void RenderImage(ImageRenderInfo renderInfo) {
      PdfImageObject image = renderInfo.GetImage();
      PdfName filter = image.Get(PdfName.FILTER) as PdfName;
      if (filter == null) {
        PdfArray pa = (PdfArray) image.Get(PdfName.FILTER);
        for (int i = 0; i < pa.Size; ++i) {
          filter = (PdfName) pa[i];
        }
      }
      if (PdfName.CCITTFAXDECODE.Equals(filter)) {
        using (Dotnet dotnetImg = image.GetDrawingImage()) {
          if (dotnetImg != null) {
            ImageNames.Add(string.Format(
              "{0}.tiff", renderInfo.GetRef().Number)
            );
            using (MemoryStream ms = new MemoryStream()) {
              dotnetImg.Save(
              ms, ImageFormat.Tiff);
              Images.Add(ms.ToArray());
            }
          }
        }
      }
    }
  }
}

如果图像正在旋转,看到这个帖子在 iText 邮件列表上;也许 PDF 文档中的某些页面已被旋转。

Since the question is still tagged w/iTextSharp might as add some code, even though it doesn't look like you're using the library here. PDF parsing support was added starting in iText[Sharp] 5.

Didn't have an test PDF with the image type you're using, but found one here (see the attachment). Here's a very simple working example in ASP.NET (HTTP handler .ashx) using that test PDF document to get you going:

<%@ WebHandler Language="C#" Class="CCITTFaxDecodeExtract" %>
using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
using Dotnet = System.Drawing.Image;
using System.Drawing.Imaging;

public class CCITTFaxDecodeExtract : IHttpHandler {
  public void ProcessRequest (HttpContext context) {
    HttpServerUtility Server = context.Server;
    HttpResponse Response = context.Response;
    string file = Server.MapPath("~/app_data/CCITTFaxDecode.pdf");
    PdfReader reader = new PdfReader(file);
    PdfReaderContentParser parser = new PdfReaderContentParser(reader);
    MyImageRenderListener listener = new MyImageRenderListener();
    for (int i = 1; i <= reader.NumberOfPages; i++) {
      parser.ProcessContent(i, listener);
    } 
    for (int i = 0; i < listener.Images.Count; ++i) {
      string path = Server.MapPath("~/app_data/" + listener.ImageNames[i]);
      using (FileStream fs = new FileStream(
        path, FileMode.Create, FileAccess.Write
      ))
      {
        fs.Write(listener.Images[i], 0, listener.Images[i].Length);
      }
    }         
  }
  public bool IsReusable { get { return false; } }
/*
 * see: TextRenderInfo & RenderListener classes here:
 * http://api.itextpdf.com/itext/
 * 
 * and Google "itextsharp extract images"
 */
  public class MyImageRenderListener : IRenderListener {
    public void RenderText(TextRenderInfo renderInfo) { }
    public void BeginTextBlock() { }
    public void EndTextBlock() { }

    public List<byte[]> Images = new List<byte[]>();
    public List<string> ImageNames = new List<string>();
    public void RenderImage(ImageRenderInfo renderInfo) {
      PdfImageObject image = renderInfo.GetImage();
      PdfName filter = image.Get(PdfName.FILTER) as PdfName;
      if (filter == null) {
        PdfArray pa = (PdfArray) image.Get(PdfName.FILTER);
        for (int i = 0; i < pa.Size; ++i) {
          filter = (PdfName) pa[i];
        }
      }
      if (PdfName.CCITTFAXDECODE.Equals(filter)) {
        using (Dotnet dotnetImg = image.GetDrawingImage()) {
          if (dotnetImg != null) {
            ImageNames.Add(string.Format(
              "{0}.tiff", renderInfo.GetRef().Number)
            );
            using (MemoryStream ms = new MemoryStream()) {
              dotnetImg.Save(
              ms, ImageFormat.Tiff);
              Images.Add(ms.ToArray());
            }
          }
        }
      }
    }
  }
}

If the image(s) is/are being rotated, see this thread on the iText mailing list; perhaps some of the pages in the PDF document have been rotated.

南烟 2024-12-24 20:20:30

至此,这是从 pdf 中提取图像并旋转它的完整代码。对于代码的长度感到抱歉。

PdfDocument document = PdfReader.Open("D:\\Sample.pdf");
PdfDictionary resources =document.pages.Elements.GetDictionary("/Resources");
PdfDictionary xObjects = resources.Elements.GetDictionary("/XObject");
if (xObjects != null)
{
    ICollection<PdfItem> items = xObjects.Elements.Values;
    // Iterate references to external objects
    foreach (PdfItem item in items)
    {
        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")
            {
                string filter = xObject.Elements.GetName("/Filter");

                if (filter.Equals("/CCITTFaxDecode"))
                {
                    int width = xObject.Elements.GetInteger(PdfImage.Keys.Width);
                    int height = xObject.Elements.GetInteger(PdfImage.Keys.Height);
                    int bpp = xObject.Elements.GetInteger(PdfImage.Keys.BitsPerComponent);

                    byte[] data = xObject.Stream.Value;
                    Tiff tiff = BitMiracle.LibTiff.Classic.Tiff.Open("D:\\sample.tif", "w");
                    tiff.SetField(TiffTag.IMAGEWIDTH, (uint)(width));
                    tiff.SetField(TiffTag.IMAGELENGTH, (uint)(height));
                    tiff.SetField(TiffTag.COMPRESSION, (uint)BitMiracle.LibTiff.Classic.Compression.CCITTFAX4);
                    tiff.SetField(TiffTag.BITSPERSAMPLE, (uint)(bpp));
                    tiff.SetField(TiffTag.STRIPOFFSETS, 187);

                    tiff.WriteRawStrip(0,data,data.Length);
                    tiff.Close();
                }
            }
        }
    }
}

By the by this is the complete code which is extracting the image from the pdf, but rotating it. Sorry about the length of the code.

PdfDocument document = PdfReader.Open("D:\\Sample.pdf");
PdfDictionary resources =document.pages.Elements.GetDictionary("/Resources");
PdfDictionary xObjects = resources.Elements.GetDictionary("/XObject");
if (xObjects != null)
{
    ICollection<PdfItem> items = xObjects.Elements.Values;
    // Iterate references to external objects
    foreach (PdfItem item in items)
    {
        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")
            {
                string filter = xObject.Elements.GetName("/Filter");

                if (filter.Equals("/CCITTFaxDecode"))
                {
                    int width = xObject.Elements.GetInteger(PdfImage.Keys.Width);
                    int height = xObject.Elements.GetInteger(PdfImage.Keys.Height);
                    int bpp = xObject.Elements.GetInteger(PdfImage.Keys.BitsPerComponent);

                    byte[] data = xObject.Stream.Value;
                    Tiff tiff = BitMiracle.LibTiff.Classic.Tiff.Open("D:\\sample.tif", "w");
                    tiff.SetField(TiffTag.IMAGEWIDTH, (uint)(width));
                    tiff.SetField(TiffTag.IMAGELENGTH, (uint)(height));
                    tiff.SetField(TiffTag.COMPRESSION, (uint)BitMiracle.LibTiff.Classic.Compression.CCITTFAX4);
                    tiff.SetField(TiffTag.BITSPERSAMPLE, (uint)(bpp));
                    tiff.SetField(TiffTag.STRIPOFFSETS, 187);

                    tiff.WriteRawStrip(0,data,data.Length);
                    tiff.Close();
                }
            }
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文