Dear,
I'm trying to make a little Windows Form app for reducing size of a PDF file containing or not some pictures.
For that, I think the best way is use PDFSharp + imageFactory to reduce image. (Using Options.FlateEncodeMode = PdfFlateEncodeMode.BestCompression; it's not enough for reducing file size).
Actually, I can reduce some of PDF (created by a Writer for example). But I can't reduce lot of PDF file created with a Scanner. (I got an error).
Code:
// Open the Original PDF File.
PdfSharp.Pdf.PdfDocument document = PdfSharp.Pdf.IO.PdfReader.Open("testFile.pdf", PdfDocumentOpenMode.Import);
// Create the new Empty PDF File
PdfSharp.Pdf.PdfDocument nouveau_doc = new PdfSharp.Pdf.PdfDocument();
foreach (PdfPage page in document.Pages)
{
PdfDictionary resources = page.Elements.GetDictionary("/Resources");
if (resources != null)
{
PdfDictionary xObjects = resources.Elements.GetDictionary("/XObject");
if (xObjects != null)
{
ICollection<PdfItem> items = xObjects.Elements.Values;
foreach (PdfItem item in items)
{
if (item is PdfReference reference)
{
// If an Image is found.
if (reference.Value is PdfDictionary xObject && xObject.Elements.GetString("/Subtype") == "/Image")
{
byte[] stream = xObject.Stream.Value;
int width = xObject.Elements.GetInteger(PdfImage.Keys.Width);
int height = xObject.Elements.GetInteger(PdfImage.Keys.Height);
using (MemoryStream inStream = new MemoryStream(stream))
{
using (MemoryStream outStream = new MemoryStream())
{
using (ImageFactory imageFactory = new ImageFactory())
{
imageFactory.Load(inStream).Format(new JpegFormat { Quality = 30 }).Resize(new System.Drawing.Size(width, height)).Resolution(96, 96).Save(outStream);
}
xObject.Stream.Value = outStream.ToArray();
}
}
}
}
}
}
}
// Add the content to a new page.
nouveau_doc.AddPage(page);
} // End of the foreach page in the PDF file.
// Finally save the new document.
nouveau_doc.Save("pdf_compressed.PDF");
This line
Code:
imageFactory.Load(inStream).Format(new JpegFormat { Quality = 30 }).Resize(new System.Drawing.Size(width, height)).Resolution(96, 96).Save(outStream);
make me this error :
Quote:
ImageProcessor.Common.Exceptions.ImageFormatException : 'Input stream is not a supported format.'
It appear the Stream have no Format ... any idea ?
Thanks a lot for help
Falcon