def add_notes(page, notes): for note in notes: # Create the location, note that the Mendeley coordinate system seems to have its Y axis inverted when # compared to the pdf library's axis. So the Y position should be flipped page_lr = page.rect corner = pdf.Point(note.x, page_lr.y1 - note.y) # Get the date if note.date == None: date = pdf.getPDFnow() else: try: date = note.date.strftime("D:%Y%m%d%H%M%SZ00'00") except: date = pdf.getPDFnow() # Make the note anot = page.addTextAnnot(corner, note.content) color = anot.colors color["fill_color"] = note.color color["stroke_color"] = note.color anot.setColors(color) anot.setOpacity(1) info = anot.info info["title"] = note.author info["content"] = note.content info["subject"] = note.content.partition("\n")[0] info["creationDate"] = date anot.setInfo(info) anot.update()
y = a.y - x * math.sqrt(3) c = fitz.Point(x, y) # top corner of drawn triangle shape.drawPolyline((a, b, c)) # draw start triangle on it shape.finish(fill=color1, closePath=True) # colorize it t0 = time.perf_counter() triangle_count = 0 triangle_count = triangle(shape, a, b, c, fill, triangle_count) # draw the fractal t1 = time.perf_counter() compute_time = round(t1 - t0, 3) shape.commit() # write the shape to the page meta = { "title": "Sierpinski Triangle with %i sub-triangles" % triangle_count, "author": "Jorj X. McKie", "subject": "Demonstration of PyMuPDF's features", "keywords": "PDF, fractal, Sierpinski, triangle", "creator": os.path.basename(__file__), "producer": "PyMuPDF v%s" % fitz.VersionBind, "creationDate": fitz.getPDFnow(), "modDate": fitz.getPDFnow(), } doc.setMetadata(meta) doc.save(outfile, deflate=True) print( "Computation time %g seconds, triangle side %g pixels, %i sub-triangles." % (compute_time, abs(b - a), triangle_count))
def make_pdf(dlg): # no file selected: treat like "QUIT" if not len(dlg.szr02.Table.data): # no files there - quit return None # create time zone value in PDF format cdate = fitz.getPDFnow() ausgabe = dlg.btn_aus.GetPath() pdf_out = fitz.open() # empty new PDF document aus_nr = 0 # current page number in output pdf_dict = {"creator": "PDF Joiner", "producer": "PyMuPDF", "creationDate": cdate, "modDate": cdate, "title": dlg.austit.Value, "author": dlg.ausaut.Value, "subject": dlg.aussub.Value, "keywords": dlg.keywords.Value} pdf_out.setMetadata(pdf_dict) # put in meta data total_toc = [] # initialize TOC #============================================================================== # process one input file #============================================================================== for zeile in dlg.szr02.Table.data: dateiname = zeile[0] doc = fitz.open(dateiname) max_seiten = len(doc) #============================================================================== # user input minus 1, PDF pages count from zero # also correct any inconsistent input #============================================================================== von = int(zeile[2]) - 1 # first PDF page number bis = int(zeile[3]) - 1 # last PDF page number von = min(max(0, von), max_seiten - 1) # "from" must be in range bis = min(max(0, bis), max_seiten - 1) # "to" must be in range rot = int(zeile[4]) # get rotation angle # now copy the page range pdf_out.insertPDF(doc, from_page = von, to_page = bis, rotate = rot) if dlg.noToC.Value: # no ToC wanted - get next file continue incr = 1 # standard increment for page range if bis < von: incr = -1 # increment for reversed sequence # list of page numbers in range pno_range = list(range(von, bis + incr, incr)) # standard bokkmark title = "infile [pp from-to of max.pages]" bm_main_title = "%s [pp. %s-%s of %s]" % \ (os.path.basename(dateiname[:-4]), von + 1, bis + 1, max_seiten) # insert standard bookmark ahead of any page range total_toc.append([1, bm_main_title, aus_nr + 1]) toc = doc.getToC(simple = False) # get file's TOC last_lvl = 1 # immunize against hierarchy gaps for t in toc: lnk_type = t[3]["kind"] # if "goto", page must be in range if (t[2] - 1) not in pno_range and lnk_type == fitz.LINK_GOTO: continue if lnk_type == fitz.LINK_GOTO: pno = pno_range.index(t[2] - 1) + aus_nr + 1 # repair hierarchy gaps by filler bookmarks while (t[0] > last_lvl + 1): total_toc.append([last_lvl + 1, "<>", pno, t[3]]) last_lvl += 1 last_lvl = t[0] t[2] = pno total_toc.append(t) aus_nr += len(pno_range) # increase output counter doc.close() doc = None #============================================================================== # all input files processed #============================================================================== if total_toc: pdf_out.setToC(total_toc) pdf_out.save(ausgabe) pdf_out.close() return ausgabe
fitz.Point(50, height - 33), # line above footer fitz.Point(50 + pspace, height - 33), color=blue, width=0.5) page.insertText( fitz.Point( 50 + pspace - plen_ftr, # insert footer height - 33 + ftr_fontsz * 1.2), footer, fontsize=ftr_fontsz, color=blue) # finally provide some metadata m = { "creationDate": fitz.getPDFnow(), # current timestamp "modDate": fitz.getPDFnow(), # current timestamp "creator": "text2pdf.py", "producer": "PyMuPDF v1.11.0", "title": "Content of file " + ifn, "subject": "Demonstrate the use of methods insertPage, insertText and drawLine", "author": "Jorj McKie" } doc.setMetadata(m) # and save the PDF doc.save(ofn, garbage=4, deflate=True) doc.close()
cropbox = +img.rect + (-5, -5, 5, 5) img.commit() p.setCropBox(cropbox) # create first pencil page (tip left) page = doc.newPage() img = page.newShape() pencil(img, fitz.Point(100,150), 100, True) cropbox = +img.rect + (-5, -5, -5, +5) img.commit() page.setCropBox(cropbox) # create second pencil page (tip right) page = doc.newPage() img = page.newShape() pencil(img, fitz.Point(440,150), 100, False) cropbox = +img.rect + (5, -5, 5, +5) img.commit() page.setCropBox(cropbox) m = {'title': "Signs and Symbols", 'author': "Jorj X. McKie", 'subject': "Create various symbols for use with showPDFpage()", 'keywords': "symbols, shapes, signs", 'creator': "shapes_and_symbols.py", 'producer': "PyMuPDF", 'creationDate': fitz.getPDFnow(), 'modDate': fitz.getPDFnow()} doc.setMetadata(m) doc.save("symbols.pdf", garbage = 4, deflate= True)
doc = fitz.open() # empty PDF while idx < num_colors: doc.insertPage(-1, width = w, height = h) # new empty page page=doc[-1] # load it for i in range(10): # row index if idx >= num_colors: break for j in range(10): # column index rect = fitz.Rect(rw*j, rh*i, rw*j + rw, rh*i + rh) # color rect cname = mylist[idx][0].lower() # color name col = mylist[idx][1:] # color tuple -> to floats col = (col[0] / 255., col[1] / 255., col[2] / 255.) page.drawRect(rect, color = col, fill = col) # draw color rect pnt1 = rect.top_left + (0, rh*0.3) # pos of color name in white pnt2 = pnt1 + (0, lheight) # pos of color name in black page.insertText(pnt1, cname, fontsize = fsize, color = white) page.insertText(pnt2, cname, fontsize = fsize, color = black) idx += 1 if idx >= num_colors: break m = {"author": "Jorj X. McKie", "producer": "PyMuPDF", "creator": "colordb.py", "creationDate": fitz.getPDFnow(), "modDate": fitz.getPDFnow(), "title": "PyMuPDF Color Database", "subject": "Sorted down by HSV values"} doc.setMetadata(m) path = os.path.dirname(os.path.abspath(__file__)) ofn = os.path.join(path, "colordbHSV.pdf") print("Writing:", ofn) doc.save(ofn, garbage = 4, deflate = True, clean=True)
triangle_count) # draw the fractal t1 = time.perf_counter() compute_time = round(t1 - t0, 3) shape.commit() # write the shape to the page meta = { "title": "Sierpinski Triangle with %i sub-triangles, %g seconds" % (triangle_count, compute_time), "author": "Jorj X. McKie", "subject": "Demonstration of PyMuPDF's features", "keywords": "PDF, fractal, Sierpinski, triangle", "creator": os.path.basename(__file__), "producer": "PyMuPDF v%s" % fitz.VersionBind, "creationDate": fitz.getPDFnow(), "modDate": fitz.getPDFnow(), } doc.setMetadata(meta) doc.save(outfile, deflate=True) print( "Computation time %g seconds, triangle side %g pixels, %i sub-triangles." % (compute_time, abs(b - a), triangle_count))
page.insertText(fitz.Point(50, 50), ifn, # header = input filename color = blue, fontsize = hdr_fontsz) page.drawLine(fitz.Point(50,60), fitz.Point(50 + pspace,60), # line below hdr color= blue, width = 0.5) page.drawLine(fitz.Point(50, height-33), # line above footer fitz.Point(50 + pspace, height - 33), color = blue, width = 0.5) page.insertText(fitz.Point(50 + pspace - plen_ftr, # insert footer height - 33 + ftr_fontsz * 1.2), footer, fontsize = ftr_fontsz, color = blue) # finally provide some metadata m = {"creationDate": fitz.getPDFnow(), # current timestamp "modDate": fitz.getPDFnow(), # current timestamp "creator": "text2pdf.py", "producer": "PyMuPDF v1.11.0", "title": "Content of file " + ifn, "subject": "Demonstrate the use of methods insertPage, insertText and drawLine", "author": "Jorj McKie"} doc.setMetadata(m) # and save the PDF doc.save(ofn, garbage=4, deflate=True) doc.close()
Dependencies: ------------- * PyMuPDF v1.17.4 * calendar (either use LocaleTextCalendar or just TextCalendar) This program creates calendars for three years in a row (starting with the one given as parameter) and stores the result in a PDF. """ import fitz import calendar import sys if not fitz.VersionBind.split(".") >= ["1", "17", "4"]: raise ValueError("Need PyMuPDF v.1.17.4 at least.") if len(sys.argv) != 2: startyear = fitz.getPDFnow()[2:6] # take current year else: startyear = sys.argv[1] if len(startyear) != 4 or not startyear.isnumeric(): raise ValueError("Start year must be 4 digits") suffix = "-%s.pdf" % startyear outfile = __file__.replace(".py", suffix) startyear = int(startyear) doc = fitz.open() # new empty PDF # font = fitz.Font("cour") # use the built-in font Courier font = fitz.Font("spacemo") # use Space Mono - a nicer mono-spaced font cal = calendar.LocaleTextCalendar(locale="de") # use your locale # cal = calendar.TextCalendar() # or stick with English