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