def export_pdf(images, hocrs, title="", default_dpi=300): """Create a searchable PDF from a pile of HOCR + JPEG""" load_invisible_font() pdf = Canvas(StdoutWrapper(), pageCompression=1) pdf.setCreator('ScanIt Cloud OCR') pdf.setTitle(title) dpi = default_dpi for i, image in enumerate(images): hocr = hocrs[i] w, h = image.size try: dpi = image.info['dpi'][0] except KeyError: pass width = w * 72 / dpi height = h * 72 / dpi pdf.setPageSize((width, height)) reportlab_pil_img = ImageReader(image) pdf.drawImage(reportlab_pil_img, 0, 0, width=width, height=height) add_text_layer(pdf, image, hocr, height, dpi) pdf.showPage() return pdf.getpdfdata()
def generate_pdf(data, file_path): _size = [540, 720] _canvas = Canvas(file_path, pagesize=letter) _canvas.setTitle(data['title']) _canvas.setAuthor(data['userid']) _style = get_style() _header = get_header(data, _style) _content = json_to_table(data['items']) _table = Table(_content) _table.setStyle( TableStyle([('BOX', (0, 0), (-1, -1), 0.25, colors.black), ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black)])) for index in range(len(_content)): _bg_color = colors.whitesmoke if index % 2 == 0 else colors.lightgrey _table.setStyle( TableStyle([('BACKGROUND', (0, index), (-1, index), _bg_color)])) _, _height = _header.wrap(_size[0], _size[1]) _header.drawOn(_canvas, 72, _size[1]) _size[1] = _size[1] - _height _, _height = _table.wrap(_size[0], _size[1]) _table.drawOn(_canvas, 72, _size[1] - _height) return _canvas.getpdfdata()
def test11_untitled(self): """Test ability to omit document title""" canvas = Canvas('') canvas.drawString(100, 750, "Hello world!") document = canvas.getpdfdata() self.printer_default.spool(document) self.assertPrintedLpr()
def make_data_layer(profile, trip): canvas = Canvas(tempfile.TemporaryFile()) canvas.setFont("Helvetica", 11) canvas.drawString(144, 705, "%s %s" % (profile.firstname, profile.lastname)) canvas.drawString(144, 684, profile.birthday) canvas.drawString(310, 684, profile.placeofbirth) canvas.drawString( 144, 665, "%s %s %s" % (profile.address, profile.zipcode, profile.city)) canvas.drawString(72, 109, f'Fait à {profile.city}') canvas.drawString(72, 93, f'Le {trip.date.strftime("%d/%m/%Y")}') canvas.drawString(310, 93, f'à {trip.date.strftime("%H:%M")}') canvas.setFont("Helvetica", 12) for reason in trip.reasons: canvas.drawString(73, reason.value.get('y'), "x") qr_path = qr.generateQR(profile, trip) canvas.drawImage(qr_path, canvas._pagesize[0] - 107, 80, 82, 82) canvas.showPage() canvas.drawImage(qr_path, 50, canvas._pagesize[1] - 390, 300, 300) if os.path.exists(qr_path): os.remove(qr_path) stream = io.BytesIO() stream.write(canvas.getpdfdata()) stream.seek(0) return stream
def process_pdf(self, image_data, hocr_data, pdf_filename): """Utility function if you'd rather get the PDF data back instead of save it automatically.""" pdf = Canvas(pdf_filename, pageCompression=1) pdf.setCreator('hocr-tools') pdf.setPageSize((self.width, self.height)) pdf.drawImage(image_data, 0, 0, width=self.width, height=self.height) pdf = self.add_text_layer(pdf, hocr_data) pdf_data = pdf.getpdfdata() return pdf_data
class Watermark(object): def __init__(self): self.canvas = Canvas('watermark.pdf', pagesize=(612, 792)) def sign(self, x, y, phrases=(), dx=0): c = self.canvas c.drawImage('../signature.png', x=x, y=y, width=120, height=100, mask='auto', preserveAspectRatio=True, anchor='sw') for phrase in phrases: y -= 14 c.drawString(x + 20 + dx, y, phrase) def page(self): self.canvas.showPage() return PdfFileReader(StringIO(self.canvas.getpdfdata())).getPage(0)
def make_data_layer(profile, trip): canvas = Canvas(tempfile.TemporaryFile()) canvas.setFont("Helvetica", 11) canvas.drawString(111, 516, "%s %s" % (profile.firstname, profile.lastname)) canvas.drawString(111, 501, profile.birthday) canvas.drawString(228, 501, profile.placeofbirth) canvas.drawString( 126, 487, "%s %s %s" % (profile.address, profile.zipcode, profile.city)) canvas.setFont("Helvetica", 12) for reason in trip.reasons: if reason.value.get('page') == 1: canvas.drawString(60, reason.value.get('y'), "x") qr_path = qr.generateQR(profile, trip) canvas.showPage() canvas.drawImage(qr_path, canvas._pagesize[0] - 107, 80, 82, 82) for reason in trip.reasons: if reason.value.get('page') == 2: canvas.drawString(60, reason.value.get('y'), "x") canvas.setFont("Helvetica", 11) canvas.drawString(72, 99, f'Fait à {profile.city}') canvas.drawString(72, 83, f'Le {trip.date.strftime("%d/%m/%Y")}') canvas.drawString(310, 83, f'à {trip.date.strftime("%H:%M")}') canvas.drawString( 72, 67, '(Date et heure de début de sortie à mentionner obligatoirement)') canvas.showPage() canvas.drawImage(qr_path, 50, canvas._pagesize[1] - 390, 300, 300) if os.path.exists(qr_path): os.remove(qr_path) stream = io.BytesIO() stream.write(canvas.getpdfdata()) stream.seek(0) return stream
def generate_barcodes(): product = request.args.get("product") sku = request.args.get("SKU") ean13 = request.args.get("EAN13") color = request.args.get("color") composition = request.args.get("composition") origin = request.args.get("origin") filename = "{}_{}_ean-sticker.pdf".format(sku, ean13) canvas = Canvas(filename, pagesize=A4) sticker = app.labelGenerator.label(ean13, product, sku, color, composition, origin) app.labelGenerator.fill_sheet(canvas, sticker) pdf_out = canvas.getpdfdata() response = make_response(pdf_out) response.headers['Content-Disposition'] = "attachment; filename={}".format( filename) response.mimetype = 'application/pdf' return response
def main(): pdfmetrics.registerFont(TTFont('Dosis', 'Dosis-Medium.ttf')) stars = [] with open('bsc5.dat', 'rb') as f: for line in f: line = '.' + line # switch to 1-based indexing if not line[62].strip(): continue # skip coordinate-less novas letter = intern(line[8:11]) if letter == ' ': letter = None h, m, s = float(line[61:63]), float(line[63:65]), float(line[65:69]) ra = (h + (m + s / 60.0) / 60.0) * tau / 24.0 d, m, s = float(line[69:72]), float(line[72:74]), float(line[76:78]) dec = (d + (m + s / 60.0) / 60.0) * tau / 360.0 mag = float(line[103:108]) stars.append((letter, ra, dec, mag)) h, w = 48, 96 c = Canvas('logo.pdf', pagesize=(w, h)) c.setFillColor('white') c.rect(0, 0, w, h, stroke=0, fill=1) c.setFillColor(bright_star_color) rotation = 10.0 * tau / 360.0 # magscale = 0.1 # For 10 degrees: x_offset = 96 -33.5 y_offset = h +37.5 # For 15 degrees: # x_offset = 96 -28.5 # y_offset = 96 +0.5 # for 45 degrees: # x_offset = 96 -13.5 # y_offset = 96 -10 small_glyphs = [] c.setFont('Helvetica', 2) for letter, ra, dec, mag in stars: # if mag > 4.0: # continue d = - (dec - quarter_tau) * 100 ra += rotation x = d * sin(ra) y = d * cos(ra) if y < -63.0 or y > -39.0: continue if x < -43.0 or x > 19.0: continue x += x_offset y += y_offset r = ((13.0 - mag) / 10.0) ** 4.0 #* magscale r = min(r, 1.0) if r < 0.5: small_glyphs.append((x, y, r)) else: if letter is not None: c.saveState() greek_letter, offset = greeks[letter] c.setFillColor(greek_color) c.drawString(x+offset, y+0.5, greek_letter) if letter == 'Alp': c.setFillColor(alpha_star_color) c.circle(x, y, r, stroke=0, fill=1) c.restoreState() if letter != 'Alp': c.circle(x, y, r, stroke=0, fill=1) else: c.circle(x, y, r, stroke=0, fill=1) c.setFillColor(dim_star_color) for x, y, r in small_glyphs: c.circle(x, y, r, stroke=0, fill=1) c.setFillColor(text_color) #, alpha=0.5) c.setFont('Dosis', 24) sw = c.stringWidth('Skyfield') c.drawString(w // 2 - sw // 2, h - 40, 'Skyfield') c.showPage() with open('logo.pdf', 'wb') as f: f.write(c.getpdfdata())
def print_many_areas(areas): init_pdf() c = Canvas('1.pdf', pagesize = A4) x = (A4[0] - BLANK_WIDTH) / 2 y = (A4[1] - 3*BLANK_HEIGHT) / 2 map_urls = [ build_map_url(area.x, area.y, area.zoom, area.marks) for area in areas ] urls_to_fetch = [] map_pngs = {} for url in map_urls: png = MapCache.get_map(url) if png: map_pngs[url] = png else: urls_to_fetch.append(url) if urls_to_fetch: pool = multiprocessing.Pool(16) fetched_pngs = pool.map(fetch_map, urls_to_fetch) pool.close() else: fetched_pngs = [] for url, png in izip(urls_to_fetch, fetched_pngs): if png is None: raise Exception("Cannot fetch {0}".format(url)) map_pngs[url] = png map_images = {} for url, png in map_pngs.iteritems(): map_images[url] = adjust_colors(Image.open(StringIO.StringIO(png)).convert('RGB')) # Saving PNG to MapCache only after creating Image from it to insure it is proper PNG for url, png in izip(urls_to_fetch, fetched_pngs): MapCache.save_map(url, png) for page_no in xrange((len(areas) + 2) / 3): page_set = areas[page_no*3 : (page_no+1)*3] c.setLineWidth(0.5) c.setStrokeGray(0.5) c.line(x, 0, x, A4[1]) c.line(x + BLANK_WIDTH, 0, x + BLANK_WIDTH, A4[1]) c.line(0, y + 3*BLANK_HEIGHT, A4[0], y + 3*BLANK_HEIGHT) print_area_blank(c, x, y + 2*BLANK_HEIGHT, areas[page_no*3 + 0], map_images[map_urls[page_no*3 + 0]]) c.line(0, y + 2*BLANK_HEIGHT, A4[0], y + 2*BLANK_HEIGHT) if len(page_set) >= 2: print_area_blank(c, x, y + BLANK_HEIGHT, areas[page_no*3 + 1], map_images[map_urls[page_no*3 + 1]]) c.line(0, y + BLANK_HEIGHT, A4[0], y + BLANK_HEIGHT) if len(page_set) >= 3: print_area_blank(c, x, y, areas[page_no*3 + 2], map_images[map_urls[page_no*3 + 2]]) c.line(0, y, A4[0], y) c.showPage() return c.getpdfdata()
def print_many_areas(areas): init_pdf() c = Canvas('1.pdf', pagesize=A4) x = (A4[0] - BLANK_WIDTH) / 2 y = (A4[1] - 3 * BLANK_HEIGHT) / 2 map_urls = [ build_map_url(area.x, area.y, area.zoom, area.marks) for area in areas ] urls_to_fetch = [] map_pngs = {} for url in map_urls: png = MapCache.get_map(url) if png: map_pngs[url] = png else: urls_to_fetch.append(url) if urls_to_fetch: pool = multiprocessing.Pool(16) fetched_pngs = pool.map(fetch_map, urls_to_fetch) pool.close() else: fetched_pngs = [] for url, png in izip(urls_to_fetch, fetched_pngs): if png is None: raise Exception("Cannot fetch {0}".format(url)) map_pngs[url] = png map_images = {} for url, png in map_pngs.iteritems(): map_images[url] = adjust_colors( Image.open(StringIO.StringIO(png)).convert('RGB')) # Saving PNG to MapCache only after creating Image from it to insure it is proper PNG for url, png in izip(urls_to_fetch, fetched_pngs): MapCache.save_map(url, png) for page_no in xrange((len(areas) + 2) / 3): page_set = areas[page_no * 3:(page_no + 1) * 3] c.setLineWidth(0.5) c.setStrokeGray(0.5) c.line(x, 0, x, A4[1]) c.line(x + BLANK_WIDTH, 0, x + BLANK_WIDTH, A4[1]) c.line(0, y + 3 * BLANK_HEIGHT, A4[0], y + 3 * BLANK_HEIGHT) print_area_blank(c, x, y + 2 * BLANK_HEIGHT, areas[page_no * 3 + 0], map_images[map_urls[page_no * 3 + 0]]) c.line(0, y + 2 * BLANK_HEIGHT, A4[0], y + 2 * BLANK_HEIGHT) if len(page_set) >= 2: print_area_blank(c, x, y + BLANK_HEIGHT, areas[page_no * 3 + 1], map_images[map_urls[page_no * 3 + 1]]) c.line(0, y + BLANK_HEIGHT, A4[0], y + BLANK_HEIGHT) if len(page_set) >= 3: print_area_blank(c, x, y, areas[page_no * 3 + 2], map_images[map_urls[page_no * 3 + 2]]) c.line(0, y, A4[0], y) c.showPage() return c.getpdfdata()