pdf_list_images.go hosted by Oembed Proxy for GitHub
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
/*
 * List images in a PDF file.  Passes through each page, goes through the content stream and finds instances of both
 * XObject Images and inline images. Also handles images referred within XObject Form content streams.
 * Additionally outputs a summary of the filters and colorspaces used by the images found.
 *
 * Run as: go run pdf_list_images.go input.pdf
 */

package main

import (
	"fmt"
	"os"

	"github.com/unidoc/unipdf/v3/common/license"
	"github.com/unidoc/unipdf/v3/contentstream"
	"github.com/unidoc/unipdf/v3/core"
	"github.com/unidoc/unipdf/v3/model"
)

var colorspaces = map[string]int{}
var filters = map[string]int{}

func init() {
	// Make sure to load your metered License API key prior to using the library.
	// If you need a key, you can sign up and create a free one at https://cloud.unidoc.io
	err := license.SetMeteredKey(os.Getenv(`UNIDOC_LICENSE_API_KEY`))
	if err != nil {
		panic(err)
	}
}

func main() {
	if len(os.Args) < 2 {
		fmt.Printf("Syntax: go run pdf_list_images.go input.pdf\n")
		os.Exit(1)
	}

	for _, inputPath := range os.Args[1:len(os.Args)] {
		fmt.Printf("Input file: %s\n", inputPath)

		err := listImages(inputPath)
		if err != nil {
			fmt.Printf("Error: %v\n", err)
			os.Exit(1)
		}
	}

	fmt.Printf("=======\nFilter summary:\n")
	for filter, instances := range filters {
		fmt.Printf(" %s: %d instance(s)\n", filter, instances)
	}
	fmt.Printf("=======\nColorspace summary:\n")
	for cs, instances := range colorspaces {
		fmt.Printf(" %s: %d instance(s)\n", cs, instances)
	}
}

// List images and properties of a PDF specified by inputPath.
func listImages(inputPath string) error {
	pdfReader, f, err := model.NewPdfReaderFromFile(inputPath, nil)
	if err != nil {
		return err
	}
	defer f.Close()

	numPages, err := pdfReader.GetNumPages()
	if err != nil {
		return err
	}
	fmt.Printf("PDF Num Pages: %d\n", numPages)

	for i := 0; i < numPages; i++ {
		fmt.Printf("-----\nPage %d:\n", i+1)

		page, err := pdfReader.GetPage(i + 1)
		if err != nil {
			return err
		}

		// List images on the page.
		err = listImagesOnPage(page)
		if err != nil {
			return err
		}
	}

	return nil
}

func listImagesOnPage(page *model.PdfPage) error {
	contents, err := page.GetAllContentStreams()
	if err != nil {
		return err
	}

	return listImagesInContentStream(contents, page.Resources)
}

func listImagesInContentStream(contents string, resources *model.PdfPageResources) error {
	cstreamParser := contentstream.NewContentStreamParser(contents)
	operations, err := cstreamParser.Parse()
	if err != nil {
		return err
	}

	processedXObjects := map[string]bool{}

	for _, op := range *operations {
		if op.Operand == "BI" && len(op.Params) == 1 {
			// Inline image.

			iimg, ok := op.Params[0].(*contentstream.ContentStreamInlineImage)
			if !ok {
				continue
			}

			img, err := iimg.ToImage(resources)
			if err != nil {
				return err
			}

			cs, err := iimg.GetColorSpace(resources)
			if err != nil {
				return err
			}

			encoder, err := iimg.GetEncoder()
			if err != nil {
				return err
			}

			fmt.Printf(" Inline image\n")
			fmt.Printf("  Filter: %s\n", encoder.GetFilterName())
			fmt.Printf("  Width: %d\n", img.Width)
			fmt.Printf("  Height: %d\n", img.Height)
			fmt.Printf("  Color components: %d\n", img.ColorComponents)
			fmt.Printf("  ColorSpace: %s\n", cs.String())
			//fmt.Printf("  ColorSpace: %+v\n", cs)
			fmt.Printf("  BPC: %d\n", img.BitsPerComponent)

			// Log filter use globally.
			filter := encoder.GetFilterName()
			if _, has := filters[filter]; has {
				filters[filter]++
			} else {
				filters[filter] = 1
			}
			// Log colorspace use globally.
			csName := "?"
			if cs != nil {
				csName = cs.String()
			}
			if _, has := colorspaces[csName]; has {
				colorspaces[csName]++
			} else {
				colorspaces[csName] = 1
			}
		} else if op.Operand == "Do" && len(op.Params) == 1 {
			// XObject.
			name := op.Params[0].(*core.PdfObjectName)

			// Only process each one once.
			_, has := processedXObjects[string(*name)]
			if has {
				continue
			}
			processedXObjects[string(*name)] = true

			_, xtype := resources.GetXObjectByName(*name)
			if xtype == model.XObjectTypeImage {
				fmt.Printf(" XObject Image: %s\n", *name)

				ximg, err := resources.GetXObjectImageByName(*name)
				if err != nil {
					return err
				}
				img, err := ximg.ToImage()
				if err != nil {
					return err
				}

				fmt.Printf("  Filter: %#v\n", ximg.Filter)
				fmt.Printf("  Width: %v\n", *ximg.Width)
				fmt.Printf("  Height: %d\n", *ximg.Height)
				fmt.Printf("  Color components: %d\n", img.ColorComponents)
				fmt.Printf("  ColorSpace: %s\n", ximg.ColorSpace.String())
				fmt.Printf("  ColorSpace: %#v\n", ximg.ColorSpace)
				fmt.Printf("  BPC: %v\n", *ximg.BitsPerComponent)

				// Log filter use globally.
				filter := ximg.Filter.GetFilterName()
				if _, has := filters[filter]; has {
					filters[filter]++
				} else {
					filters[filter] = 1
				}
				// Log colorspace use globally.
				cs := ximg.ColorSpace.String()
				if _, has := colorspaces[cs]; has {
					colorspaces[cs]++
				} else {
					colorspaces[cs] = 1
				}
			} else if xtype == model.XObjectTypeForm {
				// Go through the XObject Form content stream.
				fmt.Printf("--> XObject Form: %s\n", *name)
				xform, err := resources.GetXObjectFormByName(*name)
				if err != nil {
					return err
				}

				formContent, err := xform.GetContentStream()
				if err != nil {
					return err
				}
				fmt.Printf("xform: %#v\n", xform)
				fmt.Printf("xform res: %#v\n", xform.Resources)
				fmt.Printf("Content: %s\n", formContent)

				// Process the content stream in the Form object too:
				// XXX/TODO: Use either form resources (priority) and fall back to page resources alternatively if not found.
				if xform.Resources != nil {
					err = listImagesInContentStream(string(formContent), xform.Resources)
				} else {
					err = listImagesInContentStream(string(formContent), resources)
				}
				if err != nil {
					return err
				}
				fmt.Printf("<-- XObject Form: %s\n", *name)
			}
		}
	}

	return nil
}