Extract images and / or fonts from a PDF.
(args)
| 481 | |
| 482 | |
| 483 | def extract_objects(args): |
| 484 | """Extract images and / or fonts from a PDF.""" |
| 485 | if not args.fonts and not args.images: |
| 486 | sys.exit("neither fonts nor images requested") |
| 487 | doc = open_file(args.input, args.password, pdf=True) |
| 488 | |
| 489 | if args.pages: |
| 490 | pages = get_list(args.pages, doc.page_count + 1) |
| 491 | else: |
| 492 | pages = range(1, doc.page_count + 1) |
| 493 | |
| 494 | if not args.output: |
| 495 | out_dir = os.path.abspath(os.curdir) |
| 496 | else: |
| 497 | out_dir = args.output |
| 498 | if not (os.path.exists(out_dir) and os.path.isdir(out_dir)): |
| 499 | sys.exit("output directory %s does not exist" % out_dir) |
| 500 | |
| 501 | font_xrefs = set() # already saved fonts |
| 502 | image_xrefs = set() # already saved images |
| 503 | |
| 504 | for pno in pages: |
| 505 | if args.fonts: |
| 506 | itemlist = doc.get_page_fonts(pno - 1) |
| 507 | for item in itemlist: |
| 508 | xref = item[0] |
| 509 | if xref not in font_xrefs: |
| 510 | font_xrefs.add(xref) |
| 511 | fontname, ext, _, buffer = doc.extract_font(xref) |
| 512 | if ext == "n/a" or not buffer: |
| 513 | continue |
| 514 | outname = os.path.join( |
| 515 | out_dir, f"{fontname.replace(' ', '-')}-{xref}.{ext}" |
| 516 | ) |
| 517 | outfile = open(outname, "wb") |
| 518 | outfile.write(buffer) |
| 519 | outfile.close() |
| 520 | buffer = None |
| 521 | if args.images: |
| 522 | itemlist = doc.get_page_images(pno - 1) |
| 523 | for item in itemlist: |
| 524 | xref = item[0] |
| 525 | if xref not in image_xrefs: |
| 526 | image_xrefs.add(xref) |
| 527 | pix = recoverpix(doc, item) |
| 528 | if type(pix) is dict: |
| 529 | ext = pix["ext"] |
| 530 | imgdata = pix["image"] |
| 531 | outname = os.path.join(out_dir, "img-%i.%s" % (xref, ext)) |
| 532 | outfile = open(outname, "wb") |
| 533 | outfile.write(imgdata) |
| 534 | outfile.close() |
| 535 | else: |
| 536 | outname = os.path.join(out_dir, "img-%i.png" % xref) |
| 537 | pix2 = ( |
| 538 | pix |
| 539 | if pix.colorspace.n < 4 |
| 540 | else fitz.Pixmap(fitz.csRGB, pix) |
nothing calls this directly
no test coverage detected
searching dependent graphs…