Comments (4)
Hi, I had to create a recursive method to extract images, because some were inside other resources...
private static IEnumerable<PdfDictionary> GetXObjectImages(PdfDictionary pdfDictionary) { var resources = pdfDictionary.Elements.GetDictionary("/Resources"); if (resources != null) { var xObjects = resources.Elements.GetDictionary("/XObject"); if (xObjects != null) { foreach (var item in xObjects.Elements.Values) { if (item is PdfReference reference) { if (reference.Value is PdfDictionary xObject) { if (xObject.Elements.GetString(PdfImage.Keys.Subtype) == "/Image") { yield return xObject; } else { foreach (var xObject1 in GetXObjectImages(xObject)) { if (xObject1.Elements.GetString(PdfImage.Keys.Subtype) == "/Image") { yield return xObject1; } } } } } } } } }
from pdfsharpcore.
Hello, @robertovaldesperez
I'm not sure if it helps, but this is how I do it. I have a pdf-file which is produced by a scanner, that file contains several pages and each page has an image.
This image can be jpeg or tif (I think your format "FlatDecode" is png, if I'm not mistaken. And if so, the library probably doesn't have a straight way of converting it).
- File is already in memory stream, I go to specified page and extract the image:
public static MemoryStream ExtractPageImage(MemoryStream ms, int PageNumber)
{
if (null == ms || 0 == ms.Length) return null;
ms.Position = 0;
PdfDocument document = PdfReader.Open(ms, PdfDocumentOpenMode.ReadOnly);
if (document.Pages.Count <= PageNumber) return null;
PdfPage pdfPage = document.Pages[PageNumber];
PdfDictionary resources = pdfPage.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 (reference.Value is PdfDictionary xObject && xObject.Elements.GetString("/Subtype") == "/Image")
{
var msImage = ExportImage(xObject);
return msImage;
}
}
}
}
}
throw new Exception("image not found inside pdf-file.");
}
- Here is how I decide on the image format:
static MemoryStream ExportImage(PdfDictionary image)
{
string filter = image.Elements.GetName("/Filter");
MemoryStream msImage = filter switch
{
"/DCTDecode" => ExportJpegImage(image),
"/CCITTFaxDecode" => ExportTifImage(image),
_ => throw new Exception("\"" + filter + " is unsupported image format."),
};
Image img = Image.FromStream(msImage);
if (img.Height > img.Width)
{
img.RotateFlip(RotateFlipType.Rotate90FlipNone); // Rotates the image clockwise 90 degrees
var msRotated = new MemoryStream();
img.Save(msRotated, System.Drawing.Imaging.ImageFormat.Jpeg);
msImage.Dispose();
return msRotated;
}
return msImage;
}
- And here is a methods for jpeg and tiff:
static MemoryStream ExportJpegImage(PdfDictionary image)
{
try
{
// Fortunately JPEG has native support in PDF and exporting an image is just writing the stream to a file.
byte[] stream = image.Stream.Value;
var ms = new MemoryStream(stream);
return ms;
}
catch
{
throw new Exception("failed converting JPEG image inside PDF-file.");
}
}
static MemoryStream ExportTifImage(PdfDictionary image)
{
try
{
MemoryStream ms = new MemoryStream();
int width = image.Elements.GetInteger(PdfImage.Keys.Width);
int height = image.Elements.GetInteger(PdfImage.Keys.Height);
int bpp = image.Elements.GetInteger(PdfImage.Keys.BitsPerComponent);
int K = 0;
//https://github.com/gheeres/PDFSharp.Extensions/blob/master/Pdf/PdfDictionaryExtensions.cs - some explanations about DecodeParams and more
PdfObject oDecodeParams = image.Elements.GetObject(PdfImage.Keys.DecodeParms);
if (oDecodeParams is PdfDictionary)
if (((PdfDictionary)oDecodeParams).Elements.ContainsKey("/K"))
K = ((PdfDictionary)oDecodeParams).Elements.GetInteger("/K");
byte[] data = image.Stream.Value;
Tiff tiff = Tiff.ClientOpen("in-memory", "w", ms, new TiffStream());
tiff.SetField(TiffTag.IMAGEWIDTH, (uint)(width));
tiff.SetField(TiffTag.IMAGELENGTH, (uint)(height));
if (0 > K)
tiff.SetField(TiffTag.COMPRESSION, Compression.CCITTFAX4);
if (0 <= K)
tiff.SetField(TiffTag.COMPRESSION, Compression.CCITTFAX3);
tiff.SetField(TiffTag.BITSPERSAMPLE, (uint)(bpp));
tiff.SetField(TiffTag.SAMPLESPERPIXEL, 1);
tiff.WriteRawStrip(0, data, data.Length);
tiff.Flush();
return ms;
}
catch
{
throw new Exception("failed converting TIFF image inside PDF-file.");
}
}
I hope this helps, I did it 5 or 6 years ago and it still works perfectly.
Regards, Sergii
from pdfsharpcore.
Hi @Bogdancev, I'm going to try this code, Do you have an example of how to extract a PNG image?
from pdfsharpcore.
Hi @robertovaldesperez
Unfortunally not, I have a full control over the settings of the company scanners, so they are set up to produce jpegs or tiffs.
from pdfsharpcore.
Related Issues (20)
- Merge improvements from upstream PDFsharp
- Paragraphs added to HeaderFooter footer sections are written to the same position (and thus overlap)
- Manipulation with Gfx crops PDF page HOT 1
- Watermark Stream with negative height
- System.ArgumentException is thrown when creating XFont object with a custom font resolver
- Pdf Document Metadata and Properties are incorrect when adding UserPassword or OwnerPassword
- a release in .NET 7+ HOT 1
- Does it support adding electronic seals in PDf?
- 🛑 Still alive? HOT 3
- pdfsharpcore file size grows thrice after edit and save for header and footer
- pdfsharpcore is missing NuGet package README file
- Dependency issue with new version of the ImageSharp HOT 18
- Base package without ImageSharp
- Non ascii characters are not correctly displayed when created on Linux (Openshift)
- Exception thrown when setting trailer info element to null HOT 4
- Visual Studio detecting Venerability with SixLabours.ImageSharp dependencies HOT 6
- Cannot insert image. HOT 10
- Can we take latest SixLabors / ImageSharp version which is v3.1.4 HOT 1
- Add Attachment to PDF-File (.xml File)
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from pdfsharpcore.