我正在尝试浏览PDF中的所有图片并调整它们以减小PDF文件的大小。我在C#中使用iTextSharp。以下是我的代码。当我查看输出文件时,没有任何图像被修改。
PdfReader pdf = new PdfReader(input);
using (PdfStamper stp = new PdfStamper(pdf, output))
{
for (int i = 1; i <= pdf.NumberOfPages; i++)
{
PdfDictionary page = pdf.GetPageN(i);
PdfDictionary resources = (PdfDictionary)PdfReader.GetPdfObject(page.Get(PdfName.RESOURCES));
PdfDictionary xObjects = (PdfDictionary)PdfReader.GetPdfObject(resources.Get(PdfName.XOBJECT));
if (xObjects == null)
continue;
foreach (PdfName name in xObjects.Keys)
{
PdfObject xObj = xObjects.Get(name);
if (!xObj.IsIndirect())
continue;
//Filter non-images
PdfDictionary xObjDic = (PdfDictionary)PdfReader.GetPdfObject(xObj);
PdfName xObjType = (PdfName)PdfReader.GetPdfObject(xObjDic.Get(PdfName.SUBTYPE));
if (!PdfName.IMAGE.Equals(xObjType))
continue;
//Get embedded image
int refId = ((PRIndirectReference)xObj).Number;
PRStream objStream = (PRStream)pdf.GetPdfObject(refId);
PdfImageObject objImg = new PdfImageObject(objStream);
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(objImg.GetImageAsBytes());
//Resize
img.ScaleAbsolute(200, 200);
img.SetDpi(72, 72);
PdfReader.KillIndirect(xObj);
stp.Writer.AddDirectImageSimple(img, (PRIndirectReference)xObj);
break;
}
}
}
pdf.Close();