PDF:无法找到要压缩的图像

时间:2017-04-18 07:33:48

标签: c# itext

我有一张PDF格式的图像,我想要压缩(对于100x100显示屏几乎是1080p)。 通常,我使用此代码来压缩图片。 对于此PDF,它无法找到任何图片。我已经查看了每个xobject.Get(name),尝试找到一张没有结果的大图。 我在哪里可以找到这张图片或者我可以使用哪种方法来压缩它?

//Bind a reader to our large PDF
PdfReader reader = new PdfReader(bt);
using (MemoryStream msOut = new MemoryStream())
{
    //Bind a stamper to the file and our reader
    using (PdfStamper stamper = new PdfStamper(reader, msOut))
    {
        for (int i = 1; i <= reader.NumberOfPages; i++)
        {
            PdfDictionary page = reader.GetPageN(i);
            //Get the xobject structure
            PdfDictionary resources = (PdfDictionary)PdfReader.GetPdfObject(page.Get(PdfName.RESOURCES));
            PdfDictionary xobject = (PdfDictionary)PdfReader.GetPdfObject(resources.Get(PdfName.XOBJECT));
            if (xobject != null)
            {
                PdfObject obj;
                //Loop through each key
                foreach (PdfName name in xobject.Keys)
                {
                    obj = xobject.Get(name);
                    if (obj.IsIndirect())
                    {
                        //Get the current key as a PDF object
                        PdfDictionary imgObject = (PdfDictionary)PdfReader.GetPdfObject(obj);
                        //See if its an image
                        if (imgObject != null && imgObject.Get(PdfName.SUBTYPE).Equals(PdfName.IMAGE))
                        {
                            //NOTE: There's a bunch of different types of filters, I'm only handing the simplest one here which is basically raw JPG, you'll have to research others
                            if (imgObject.Get(PdfName.FILTER).Equals(PdfName.DCTDECODE))
                            {
                                byte[] oldBytes = PdfReader.GetStreamBytesRaw((PRStream)imgObject);
                                byte[] newBytes;
                                using (MemoryStream sourceMS = new MemoryStream(oldBytes))
                                using (System.Drawing.Image oldImage = Bitmap.FromStream(sourceMS))
                                    newBytes = ConvertImageToBytes(oldImage);

                                iTextSharp.text.Image compressedImage = iTextSharp.text.Image.GetInstance(newBytes);
                                PdfReader.KillIndirect(obj);
                                stamper.Writer.AddDirectImageSimple(compressedImage, (PRIndirectReference)obj);
                            }
                        }
                    }
                }
            }
        }
    }
    return msOut.ToArray();
}

顺便说一句,我已经尝试使用stamper.SetFullCompression或`reader.SetPageContent(1,reader.GetPageContent(1),PdfStream.BEST_COMPRESSION);.尺寸几乎保持不变。

0 个答案:

没有答案