def drawOn(self, canv, x, y, _sW=0): """ translates Bounding Box and scales the given canvas """ if _sW > 0 and hasattr(self, 'hAlign'): a = self.hAlign if a in ('CENTER', 'CENTRE', TA_CENTER): x += 0.5*_sW elif a in ('RIGHT', TA_RIGHT): x += _sW elif a not in ('LEFT', TA_LEFT): raise ValueError("Bad hAlign value " + str(a)) xobj = self.xobj xobj_name = makerl(canv._doc, xobj) xscale = self.drawWidth/self._w yscale = self.drawHeight/self._h x -= xobj.BBox[0] * xscale y -= xobj.BBox[1] * yscale canv.saveState() canv.translate(x, y) canv.scale(xscale, yscale) canv.doForm(xobj_name) canv.restoreState()
def create_card_face(c, domain, category, header_text, footer_text, frame_colour, content_pdf_fn, offset=0, key_ring=1): # Colour frame c.setFillColorRGB(frame_colour[0], frame_colour[1], frame_colour[2]) c.roundRect(0 + offset, 0, FACE_DIM[0], FACE_DIM[1], radius=OUTER_ROUNDED_RAD, stroke=0, fill=1) # Content space c.setFillColorRGB(1, 1, 1) c.roundRect(FACE_MARGINS[3] + offset, FACE_MARGINS[2], CONTENT_DIM[0], CONTENT_DIM[1], radius=INNER_ROUNDED_RAD, stroke=0, fill=1) # Key ring cut-out, 0 = none, 1 = left, 2 = right if key_ring == 1: c.circle(0, DOCUMENT_DIM[1], KEY_RING_RAD, stroke=0, fill=1) elif key_ring == 2: c.circle(DOCUMENT_DIM[0], DOCUMENT_DIM[1], KEY_RING_RAD, stroke=0, fill=1) # Domain / Caetgory text c.setFont('Helvetica', 10, leading = None) c.drawCentredString(FACE_DIM[0]/2 + offset, FACE_DIM[1] - 0.47*cm, '- ' + domain.title() + ' -') # c.drawCentredString(FACE_DIM[0]/2 + offset, FACE_DIM[1] - 0.47*cm, domain.title() + ' / ' + category.title()) # Header text c.setFont('Helvetica-Bold', 20, leading = None) c.drawCentredString(FACE_DIM[0]/2 + offset, FACE_DIM[1] - 1.23*cm, header_text) # Footer text c.setFont('Helvetica', 8, leading = None) c.drawCentredString(FACE_DIM[0]/2 + offset, 0.15*cm, footer_text) # Include contents c.setFillColorRGB(0, 0, 0) page = pagexobj(PdfReader(content_pdf_fn).pages[0]) c.saveState() c.translate(FACE_MARGINS[3] + offset, FACE_MARGINS[2]) c.doForm(makerl(c, page)) c.restoreState()
def beforeDrawPage(self, canvas, doc): """Draws the background before anything else""" canvas.saveState() rl_obj = makerl(canvas, self.page_template) canvas.scale(self.page_xscale, self.page_yscale) canvas.doForm(rl_obj) canvas.restoreState()
def make_pdf(outfn, xobjpairs): canvas = Canvas(outfn) for xobjlist in xobjpairs: x = y = 0 for xobj in xobjlist: x += xobj.BBox[2] y = max(y, xobj.BBox[3]) canvas.setPageSize((x,y)) # Handle blank back page if len(xobjlist) > 1 and xobjlist[0] == xobjlist[-1]: xobjlist = xobjlist[:1] x = xobjlist[0].BBox[2] else: x = 0 y = 0 for xobj in xobjlist: canvas.saveState() canvas.translate(x, y) canvas.doForm(makerl(canvas, xobj)) canvas.restoreState() x += xobj.BBox[2] canvas.showPage() canvas.save()
def control_forms ( pieces, output ): """Write a pdf file to 'output', and generate control forms (one or more pages each) for 'pieces'. """ c = Canvas ( output, pagesize=letter ) pdf = PdfReader ( settings.ARTSHOW_BLANK_CONTROL_FORM ) xobj = pagexobj ( pdf.pages[0] ) rlobj = makerl ( c, xobj ) for artist, piecegroup in group_pieces_by_artist_and_n ( pieces, PIECES_PER_CONTROL_FORM ): c.doForm ( rlobj ) text_into_box ( c, settings.ARTSHOW_SHOW_YEAR, 2.4, 10.3, 3.05, 10.6 ) text_into_box ( c, unicode(artist.artistid), 6.6, 10.25, 8.0, 10.5 ) text_into_box ( c, artist.person.name, 1.7, 9.875, 4.1, 10.225, style=left_align_style ) text_into_box ( c, artist.artistname(), 1.7, 9.5, 4.1, 9.85, style=left_align_style ) text_into_box ( c, artist.person.address1 + " " + artist.person.address2, 1.7, 9.125, 4.1, 9.475, style=left_align_style ) text_into_box ( c, artist.person.city, 1.7, 8.75, 4.1, 9.1, style=left_align_style ) text_into_box ( c, artist.person.state, 1.7, 8.375, 4.1, 8.725, style=left_align_style ) text_into_box ( c, artist.person.postcode, 1.7, 8.0, 4.1, 8.35, style=left_align_style ) text_into_box ( c, artist.person.country, 1.7, 7.625, 4.1, 7.975, style=left_align_style ) text_into_box ( c, artist.person.phone, 1.7, 7.25, 4.1, 7.6, style=left_align_style ) text_into_box ( c, artist.person.email, 4.9, 9.875, 8.0, 10.225, style=left_align_style, fontSize=16 ) text_into_box ( c, ", ".join ( [agent.person.name for agent in artist.agent_set.all()] ), 5.9, 7.625, 8.0, 7.975, style=left_align_style ) for i, piece in enumerate(piecegroup): if piece is None: continue y0 = 6.45 - i*0.25 y1 = 6.675 - i*0.25 text_into_box ( c, unicode(piece.pieceid), 0.5, y0, 1.0, y1 ) text_into_box ( c, piece.name, 1.0, y0, 4.0, y1, style=left_align_style ) text_into_box ( c, yn(piece.adult), 4.0, y0, 4.5, y1 ) text_into_box ( c, priceornfs(piece.not_for_sale,piece.min_bid), 4.5, y0, 5.25, y1 ) text_into_box ( c, buynoworna(piece.buy_now), 5.25, y0, 6.0, y1 ) c.showPage () c.save ()
def drawOn(self, canv, x, y, _sW=0): if _sW > 0 and hasattr(self, 'hAlign'): a = self.hAlign if a in ('CENTER', 'CENTRE', TA_CENTER): x += 0.5*_sW elif a in ('RIGHT', TA_RIGHT): x += _sW elif a not in ('LEFT', TA_LEFT): raise ValueError("Bad hAlign value " + str(a)) xobj = self.xobj xobj_name = makerl(canv._doc, xobj) xscale = self.drawWidth/self._w yscale = self.drawHeight/self._h x -= xobj.BBox[0] * xscale y -= xobj.BBox[1] * yscale x_ = x + self.drawWidth * sin(radians(self.rotation)) y_ = y canv.saveState() canv.translate(x_, y_) canv.rotate(self.rotation) canv.scale(xscale, yscale) canv.doForm(xobj_name) canv.restoreState()
def beforeDrawPage(self, canvas, doc): "All drawing" canvas.saveState() rl_obj = makerl(canvas, self.page_template) canvas.scale(self.page_xscale, self.page_yscale) canvas.doForm(rl_obj) canvas.restoreState() self.canvas = canvas # store canvas for reuse for abspar in self.abspars: self._putAbsParagraph(*abspar) for absprim in self.absprims: self._putAbsPrim(*absprim)
def load_pdf_as_form(canvas, path): """ Convert a pdf file into a reportlab object :param canvas: Reportlab Canvas object the form may be written to :param path: path to pdf file to open :return: a reportlab object that may be drawn using canvas.doForm(obj) """ pdf = PdfReader(path) xobj = pagexobj(pdf.pages[0]) reportlab_obj = makerl(canvas, xobj) return reportlab_obj
def go(inpfn, firstpage, lastpage): firstpage, lastpage = int(firstpage), int(lastpage) outfn = 'subset_%s_to_%s.%s' % (firstpage, lastpage, os.path.basename(inpfn)) pages = PdfReader(inpfn).pages pages = [pagexobj(x) for x in pages[firstpage-1:lastpage]] canvas = Canvas(outfn) for page in pages: canvas.setPageSize(tuple(page.BBox[2:])) canvas.doForm(makerl(canvas, page)) canvas.showPage() canvas.save()
def addpage(canvas, allpages): pages = allpages[:4] del allpages[:4] x_max = max(page.BBox[2] for page in pages) y_max = max(page.BBox[3] for page in pages) canvas.setPageSize((x_max, y_max)) for index, page in enumerate(pages): x = x_max * (index & 1) / 2.0 y = y_max * (index <= 1) / 2.0 canvas.saveState() canvas.translate(x, y) canvas.scale(0.5, 0.5) canvas.doForm(makerl(canvas, page)) canvas.restoreState() canvas.showPage()
def drawOn(self, canv, x, y, _sW=0): if _sW > 0 and hasattr(self, 'hAlign'): a = self.hAlign if a in ('CENTER', 'CENTRE', TA_CENTER): x += 0.5 * _sW elif a in ('RIGHT', TA_RIGHT): x += _sW elif a not in ('LEFT', TA_LEFT): raise ValueError("Bad hAlign value " + str(a)) xobj = self.xobj xobj_name = makerl(canv._doc, xobj) xscale = self.drawWidth / self._imgw yscale = self.drawHeight / self._imgh canv.saveState() canv.translate(x, y) canv.scale(xscale, yscale) canv.doForm(xobj_name) canv.restoreState()
def drawOn(self, canv, x, y, _sW=0): if _sW > 0 and hasattr(self, 'hAlign'): a = self.hAlign if a in ('CENTER', 'CENTRE', TA_CENTER): x += 0.5*_sW elif a in ('RIGHT', TA_RIGHT): x += _sW elif a not in ('LEFT', TA_LEFT): raise ValueError("Bad hAlign value " + str(a)) canv.saveState() img = self.img_data if isinstance(img, PdfDict): xscale = self.img_width / img.BBox[2] yscale = self.img_height / img.BBox[3] canv.translate(x, y) canv.scale(xscale, yscale) canv.doForm(makerl(canv, img)) else: canv.drawImage(img, x, y, self.img_width, self.img_height) canv.restoreState()
def render(self, rectangle, data): page = self.pagexobj # Scale and translate. w, h = page.BBox[2] - page.BBox[0], page.BBox[3] - page.BBox[1] x_scale = rectangle.w / w y_scale = rectangle.h / h scale = min(x_scale, y_scale) extra_x = (rectangle.w - w * scale)*0.5 extra_y = (rectangle.h - h * scale)*0.5 # Include the pdf as a form. c = data['output'] c.saveState() c.translate(rectangle.x, rectangle.y) c.translate(extra_x, extra_y) c.scale(scale, scale) c.translate(page.BBox[0], page.BBox[1]) c.doForm(makerl(c, page)) c.restoreState()
def render(self, rectangle, data): page = self.pagexobj # Scale and translate. w, h = page.BBox[2] - page.BBox[0], page.BBox[3] - page.BBox[1] x_scale = rectangle.w / w y_scale = rectangle.h / h scale = min(x_scale, y_scale) extra_x = (rectangle.w - w * scale) * 0.5 extra_y = (rectangle.h - h * scale) * 0.5 # Include the pdf as a form. c = data['output'] c.saveState() c.translate(rectangle.x, rectangle.y) c.translate(extra_x, extra_y) c.scale(scale, scale) c.translate(page.BBox[0], page.BBox[1]) c.doForm(makerl(c, page)) c.restoreState()
def drawOn(self, canv, x, y, _sW=0): if _sW > 0 and hasattr(self, 'hAlign'): a = self.hAlign if a in ('CENTER', 'CENTRE', TA_CENTER): x += 0.5 * _sW elif a in ('RIGHT', TA_RIGHT): x += _sW elif a not in ('LEFT', TA_LEFT): raise ValueError("Bad hAlign value " + str(a)) canv.saveState() img = self.img_data if isinstance(img, PdfDict): xscale = self.img_width / img.BBox[2] yscale = self.img_height / img.BBox[3] canv.translate(x, y) canv.scale(xscale, yscale) canv.doForm(makerl(canv, img)) else: canv.drawImage(img, x, y, self.img_width, self.img_height) canv.restoreState()
def _insert_pdf_or_image(self, path: Path): """ Checks whether the given file is a PDF or an image, and performs the appropriate actions to add it to the main PDF. """ if path.suffix in [".pdf", ".PDF"]: pages = PdfReader(path).pages pages = [buildxobj.pagexobj(page) for page in pages] for page in pages: self.canvas.setPageSize((page.BBox[2], page.BBox[3])) self.canvas.doForm(toreportlab.makerl(self.canvas, page)) self._finish_page() elif path.suffix[1:] in FILE_TYPES: # treat path as an image self.canvas.setPageSize(pagesizes.letter) page_w, page_h = self.canvas._pagesize # Rotate landscape images to fit portrait page img = Image.open(path) img_ratio = img.size[0] / img.size[1] if img_ratio > 1 and self.rotate_landscape_pics: self.canvas.saveState() self.canvas.rotate(-90) w, h = 0.9 * page_h, 0.9 * page_w rotated = True x = (-w - page_h) / 2 y = (page_w - h) / 2 # x = (page_h - w) / 2 # y = (-page_w - h) / 2 else: w, h = 0.9 * page_w, 0.9 * page_h x = (page_w - w) / 2 y = (page_h - h) / 2 rotated = False self.canvas.drawImage(path, x, y, w, h, preserveAspectRatio=True) if rotated: self.canvas.restoreState() self._finish_page() else: raise SyntaxError(f"{path} is not a supported type: {FILE_TYPES}")
def createFirstPage(self): c = canvas.Canvas(self.path + 'firstPage.pdf', pagesize=(6 * inch, 9 * inch)) pages = PdfReader(self.path + 'frames\\' + 'Frame3.pdf').pages pages = [pagexobj(x) for x in pages] for page in pages: c.setPageSize((page.BBox[2], page.BBox[3])) c.doForm(makerl(c, page)) c.setFillColorRGB(0 / 256, 0 / 256, 6 / 256) c.setFont("SegoeUI", 14) text = "English - " + self.lang + " - First Edition" c.drawCentredString(3 * inch, 8 * inch, text) p = Paragraph(self.engTitle, self.styles['firstPageTitle']) p.wrapOn(c, ((454 / 96)) * inch, 3 * inch) p.drawOn(c, ((6 - (453 / 96)) / 2) * inch, 4.1 * inch) p = Paragraph(self.otherTitle, self.styles['firstPageTitle']) x, y = p.wrapOn(c, ((454 / 96)) * inch, 3 * inch) p.drawOn(c, ((6 - (453 / 96)) / 2) * inch, 3.8 * inch - y) c.save() M = PdfFileMerger() M.append(self.path + "firstPage.pdf") M.append(self.path + 'frames\\' + "Frame54.pdf") M.write(self.path + "First2Pages.pdf") M.close() M = PdfFileMerger() M.append(self.path + "files\\" + self.docName + "English-" + self.lang + ".pdf") M.write(self.path + "convert.pdf") M.close() M = PdfFileMerger() M.append(self.path + "First2Pages.pdf") M.append(self.path + "convert.pdf") M.write(self.path + "files/" + self.docName + "English-" + self.lang + ".pdf") M.close() os.remove(self.path + "convert.pdf") os.remove(self.path + "firstPage.pdf") os.remove(self.path + "First2Pages.pdf")
def insert_text_output_pdfrw(pdf_file_path, insert_text): """ 既存のPDFファイルに文字を挿入し、別名で出力します :param pdf_file_path: 既存のPDFファイルパス :param insert_text: 挿入するテキスト :return: """ from pdfrw import PdfReader from pdfrw.buildxobj import pagexobj from pdfrw.toreportlab import makerl from reportlab.pdfgen import canvas from reportlab.pdfbase.cidfonts import UnicodeCIDFont from reportlab.pdfbase import pdfmetrics from reportlab.lib.units import mm # 出力名 output_name = "pdfrw.pdf" # PDF新規作成 cc = canvas.Canvas(output_name) # フォントの設定 font_name = "HeiseiKakuGo-W5" pdfmetrics.registerFont(UnicodeCIDFont(font_name)) cc.setFont(font_name, 16) # 既存ページ読み込み page = PdfReader(pdf_file_path, decompress=False).pages # 1ページ目をオブジェクトに pp = pagexobj(page[0]) cc.doForm(makerl(cc, pp)) # 挿入位置(mm指定) target_x, target_y = 10 * mm, 10 * mm # 文字列挿入 cc.drawString(target_x, target_y, insert_text) cc.showPage() # 保存 cc.save()
def drawOn(self, canv, x, y, _sW=0, width=0, height=0): if _sW > 0 and hasattr(self, 'hAlign'): a = self.hAlign if a in ('CENTER', 'CENTRE', TA_CENTER): x += 0.5 * _sW elif a in ('RIGHT', TA_RIGHT): x += _sW elif a not in ('LEFT', TA_LEFT): raise ValueError("Bad hAlign value " + str(a)) xobj = self.xobj xobj_name = makerl(canv._doc, xobj) xscale = (width or self.drawWidth) / xobj.w yscale = (height or self.drawHeight) / xobj.h x -= xobj.x * xscale y -= xobj.y * yscale canv.saveState() canv.translate(x, y) canv.scale(xscale, yscale) canv.doForm(xobj_name) canv.restoreState()
def add_logo(pdf_name: str, ): """ Adds logo at the top for all pages in the pdf name Args: pdf_name: Returns: None. Updates the input pdf """ input_file = pdf_name output_file = pdf_name # Get pages reader = PdfReader(input_file) pages = [pagexobj(p) for p in reader.pages] # Compose new pdf canvas = Canvas(output_file) for page_num, page in enumerate(pages, start=1): # Add page canvas.setPageSize((page.BBox[2], page.BBox[3])) canvas.doForm(makerl(canvas, page)) canvas.saveState() # canvas.setStrokeColorRGB(0, 0, 0) canvas.restoreState() # Add Logo canvas.drawImage(StaticFileParameters.ra_logo_location, 650, 550, 111.750, 39) canvas.showPage() # Save pdf canvas.save()
def draw_contacts(self): ctx = self.ctx ctx.saveState() for i, l in enumerate(self.contacts): text = l[0] pdf_filename = l[1] spacing = self.contact_spacing if i > 0 else 0 ctx.translate(0, -(spacing + text.height)) ctx = self.ctx ctx.setFillColor(text.colour) ctx.setFont(text.font, text.font_size) w = 17 if '@' in str(text): # Draw character by character # in order to control colours ctx.setFillColor(black) for c in str(text): if c == '@': ctx.setFillColor(text.colour) ctx.drawString(w, 0, c) w += stringWidth(c, text.font, text.scale) else: ctx.drawString(w, 0, str(text)) pdf = PdfReader(pdf_filename).pages[0] pdf = pagexobj(pdf) ctx.saveState() ctx.translate((12 - pdf.w) / 2, -(pdf.h - text.height) / 2 + 1) ctx.doForm(makerl(ctx, pdf)) ctx.restoreState() ctx.restoreState()
def bidder_agreement(bidder, output): from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont pdfmetrics.registerFont(TTFont(*settings.ARTSHOW_BARCODE_FONT)) c = Canvas(output, pagesize=letter) pdf = PdfReader(settings.ARTSHOW_BLANK_BIDDER_AGREEMENT) xobj = pagexobj(pdf.pages[0]) rlobj = makerl(c, xobj) c.translate(0, 5.5 * inch) c.doForm(rlobj) text_into_box(c, u"*P" + unicode(bidder.person.id) + u"*", 3.5, 4.8, 5.5, 5.05, fontSize=14, style=barcode_style) text_into_box(c, "Ref. " + unicode(bidder.person.id), 3.5, 4.55, 5.5, 4.75, fontSize=10) text_into_box(c, bidder.person.reg_id, 6.2, 1.35, 7.7, 1.6, fontSize=12) text_into_box(c, bidder.person.name, 1.3, 1.4, 5.2, 1.7, fontSize=14) text_into_box(c, bidder.at_con_contact, 2.1, 0.5, 5.2, 0.8, fontSize=12) c.showPage() c.save()
def grid_overlay(infile, outfile=sys.stdout, pagesize=letter, lpi=10): """Read PDF file 'infile'. Generates a new PDF file to 'outfile' containing the first page (only) of infile, with a 'lpi' grid overlaid. """ c = Canvas(outfile, pagesize=pagesize) pdf = PdfReader(infile) xobj = pagexobj(pdf.pages[0]) rlobj = makerl(c, xobj) c.doForm(rlobj) xmax = 9 ymax = 12 thickline = 0.5 thinline = 0.1 for x in range(0, xmax): c.setLineWidth(thickline) for xx in range(0, lpi): x0 = (x + (float(xx) / lpi)) * inch c.line(x0, 0, x0, ymax * inch) c.setLineWidth(thinline) for y in range(0, ymax): c.setLineWidth(thickline) for yy in range(0, lpi): y0 = (y + (float(yy) / lpi)) * inch c.line(0, y0, xmax * inch, y0) c.setLineWidth(thinline) c.showPage() c.save()
def draw_card_face(self, c, card_face, domain, colour_scheme, frame_layout, page_nr, offset = 0): colour = colour_scheme[domain] # Colour frame c.setFillColorRGB(colour[0], colour[1], colour[2]) c.roundRect(0 + offset, 0, frame_layout['card']['width']*cm, frame_layout['card']['height']*cm, radius=frame_layout['border']['outer_corner_radius']*cm, stroke=0, fill=1) # Content space c.setFillColorRGB(1, 1, 1) c.roundRect(frame_layout['border']['left']*cm + offset, frame_layout['border']['bottom']*cm, frame_layout['content']['width']*cm, frame_layout['content']['height']*cm, radius=frame_layout['border']['inner_corner_radius']*cm, stroke=0, fill=1) # Key ring cut-out: 0 = none, 1 = top left, 2 = top right if page_nr == 1: c.circle(0, frame_layout['card_spread']['height']*cm, frame_layout['key_ring']['radius']*cm, stroke=0, fill=1) elif page_nr == 2: c.circle(frame_layout['card_spread']['width']*cm, frame_layout['card_spread']['height']*cm, frame_layout['key_ring']['radius']*cm, stroke=0, fill=1) # Domain / Caetgory text c.setFont('Helvetica', 10, leading = None) c.drawCentredString(frame_layout['card']['width']*cm/2 + offset, frame_layout['card']['height']*cm - 0.47*cm, '- ' + domain.title() + ' -') # Header text c.setFont('Helvetica-Bold', 20, leading = None) c.drawCentredString(frame_layout['card']['width']*cm/2 + offset, frame_layout['card']['height']*cm - 1.23*cm, card_face.header) # Footer text c.setFont('Helvetica', 8, leading = None) c.drawCentredString(frame_layout['card']['width']*cm/2 + offset, 0.15*cm, frame_layout['static_text']['footer']) # Include contents c.setFillColorRGB(0, 0, 0) page = pagexobj(PdfReader(card_face.content_path).pages[0]) c.saveState() c.translate(frame_layout['border']['left']*cm + offset, frame_layout['border']['bottom']*cm) c.doForm(makerl(c, page)) c.restoreState()
def drawOn(self, canv, x, y, _sW=0): if _sW > 0 and hasattr(self, 'hAlign'): hor_align = self.hAlign if hor_align in ('CENTER', 'CENTRE', TA_CENTER): x += 0.5 * _sW elif hor_align in ('RIGHT', TA_RIGHT): x += _sW elif hor_align not in ('LEFT', TA_LEFT): raise ValueError("Bad hAlign value " + str(hor_align)) xobj = self.xobj xobj_name = makerl(canv._doc, xobj) xscale = self.draw_width / self._w yscale = self.draw_height / self._h x -= xobj.BBox[0] * xscale y -= xobj.BBox[1] * yscale canv.saveState() canv.translate(x, y) canv.scale(xscale, yscale) canv.doForm(xobj_name) canv.restoreState()
def make_four_up(fn, ofn, bleed=None, scale=1.0, crop_marks=None, margin=None): scale = float(scale) pages = PdfReader(fn).pages pages = pad_pages(pages) num_pages = len(pages) pw, ph = get_page_size(pages) pages = [pagexobj(x) for x in pages] toolboxprint( "Document page size : %4.0f x %4.0f pts ( %4.0f x %4.0f mm) ( %5.2f x %5.2f in)" % (pw, ph, PTS2MM(pw), PTS2MM(ph), PTS2IN(pw), PTS2IN(ph))) w, h = 2.0 * pw * scale, ph * scale if abs(scale - 1.0) > 0: print(crayons.yellow("Rescaling document pages by %.2fx" % (scale))) toolboxprint( "4-up page size : %4.0f x %4.0f pts ( %4.0f x %4.0f mm) ( %5.2f x %5.2f in)" % (w, h, PTS2MM(w), PTS2MM(h), PTS2IN(w), PTS2IN(h))) doc_style = {"width": w, "height": h} doc = Document(ofn) total_bleed = 0 if bleed is not None: bleed = float(bleed) toolboxprint("Bleed size : %4.0f pts (%4.0f mm) ( %5.3f in)" % (float(bleed), PTS2MM(bleed), PTS2IN(bleed))) total_bleed += float(bleed) if margin is not None: margin = float(margin) toolboxprint("Margin size : %4.0f pts (%4.0f mm) ( %5.3f in)" % (float(margin), PTS2MM(margin), PTS2IN(margin))) total_bleed += float(margin) doc.page_end_callbacks = [] if crop_marks is not None: crop_marks = float(crop_marks) crop_callback = CropMarksCallback(length=crop_marks) crop_callback.style["line-colour"] = (0.5, 0.5, 0.5) doc.page_end_callbacks.append(crop_callback) toolboxprint("Adding crop marks : %4.0f pts (%4.0f mm) ( %5.3f in)" % (crop_marks, PTS2MM(crop_marks), PTS2IN(crop_marks))) doc.set_page_size(doc_style, with_bleed=total_bleed) if total_bleed > 0: wb, hb = doc.bleed_rect.width, doc.bleed_rect.height toolboxprint( "4-up with bleed : %4.0f x %4.0f pts ( %4.0f x %4.0f mm) ( %5.2f x %5.2f in)" % (wb, hb, PTS2MM(wb), PTS2MM(hb), PTS2IN(wb), PTS2IN(hb))) doc._doc_start() for idx, page in enumerate(pages): ridx = four_up_index(idx, num_pages) if idx % 4 == 0: print(crayons.green("Sheet : %d" % (int((idx + 4) / 4)))) toolboxprint(" Adding page : %3d / %-3d -> %3d" % (ridx + 1, num_pages, idx + 1)) if (idx + 1) % 2 == 0: toolboxprint(" Page break : %d" % (int((idx + 1) / 2))) x = w * (idx & 1) / 2.0 y = 0 if total_bleed > 0: x += float(total_bleed) y += float(total_bleed) edges = get_edge_colours(fn, ridx, scale) if idx & 0x01 == 0: # left page bleeds draw_bleed_rect(doc, "left", "top", edges, margin) draw_bleed_rect(doc, "left", "left", edges, margin) draw_bleed_rect(doc, "left", "bottom", edges, margin) else: # right page bleeds draw_bleed_rect(doc, "right", "top", edges, margin) draw_bleed_rect(doc, "right", "right", edges, margin) draw_bleed_rect(doc, "right", "bottom", edges, margin) doc.c.saveState() doc.c.translate(x, y) doc.c.scale(scale, scale) doc.c.doForm(makerl(doc.c, pages[ridx])) doc.c.restoreState() if (idx + 1) % 2 == 0 and (idx + 1) < num_pages: doc.page_break() doc._doc_end()
left_margin = 10 * PT_PER_MM card.move(left_margin, card.height / 2 - card.total_text_height / 2) card.draw() card.ctx.restoreState() ######## # LOGO # ######## card.ctx.saveState() logo = PdfReader('logo.pdf').pages[0] logo = pagexobj(logo) h = card.height / 2 + card.total_text_height / 2 card.move(card.width - logo.w - 10 * PT_PER_MM, h + ((card.height - h - logo.h) / 2)) card.ctx.doForm(makerl(card.ctx, logo)) card.ctx.restoreState() ################# # EMAIL & PHONE # ################# text = Text('*****@*****.**', colour=grey, scale=3.5 * PT_PER_MM) card.add_contact(text, 'email.pdf') text = Text('04 0304 8574', colour=grey, scale=3.5 * PT_PER_MM) card.add_contact(text, 'phone.pdf') card.ctx.saveState() card.ctx.translate( left_margin,
input_file = "inputfile.pdf" output_file = "my_file_with_footer.pdf" # Get pages reader = PdfReader(input_file) pages = [pagexobj(p) for p in reader.pages] # Compose new pdf canvas = Canvas(output_file) for page_num, page in enumerate(pages, start=1): # Add page canvas.setPageSize((page.BBox[2], page.BBox[3])) canvas.doForm(makerl(canvas, page)) # Draw header header_text = "Jhon institute" x = 180 canvas.saveState() canvas.setStrokeColorRGB(0, 0, 0) canvas.drawImage('input_logo.jpg', height=60, width=110, x=60, y=700) canvas.setFont('Times-Roman', 14) canvas.drawString(page.BBox[2] - x, 730, header_text) # Draw footer footer_text = "It’s easy to play any musical instrument: "+"\n" + " " \ "all you have to do is touch the right key at the right time and the instrument will play itself." x = 70 canvas.setStrokeColorRGB(0, 0, 0) canvas.setLineWidth(0.5) canvas.setFont('Times-Roman', 12)
def bid_sheets ( pieces, output ): from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont pdfmetrics.registerFont(TTFont(*settings.ARTSHOW_BARCODE_FONT)) c = Canvas(output,pagesize=letter) pdf = PdfReader ( settings.ARTSHOW_BLANK_BID_SHEET ) xobj = pagexobj ( pdf.pages[0] ) rlobj = makerl ( c, xobj ) nfs_pdf = PdfReader ( settings.ARTSHOW_BLANK_NFS_SHEET ) nfs_xobj = pagexobj ( nfs_pdf.pages[0] ) nfs_rlobj = makerl ( c, nfs_xobj ) sheet_offsets = [ (0,5.5), (4.25,5.5), (0,0), (4.25,0), ] sheets_per_page = len(sheet_offsets) sheet_num = 0 pieceiter = iter(pieces) if artshow_settings.ARTSHOW_BID_SHEET_PRECOLLATION: pieceiter = precollate_pieces(pieceiter) last_artist = None try: piece = pieceiter.next () while True: try: for sheet_num in range(sheets_per_page): if artshow_settings.ARTSHOW_BID_SHEET_PRECOLLATION: if piece is None: piece = pieceiter.next() continue else: if piece.artist != last_artist and sheet_num != 0: continue c.saveState () c.translate ( sheet_offsets[sheet_num][0]*inch, sheet_offsets[sheet_num][1]*inch ) if piece.not_for_sale: c.doForm ( nfs_rlobj ) else: c.doForm ( rlobj ) c.saveState () c.setLineWidth ( 4 ) c.setFillColorRGB ( 1, 1, 1 ) c.setStrokeColorRGB ( 1, 1, 1 ) c.roundRect ( 1.1875*inch, 4.4375*inch, 1.75*inch, 0.5*inch, 0.0675*inch, stroke=True, fill=True ) c.restoreState () text_into_box ( c, u"*A"+unicode(piece.artist.artistid)+u"P"+unicode(piece.pieceid)+u"*", 1.3125, 4.6, 2.8125, 4.875, fontSize=13, style=barcode_style ) text_into_box ( c, "Artist "+unicode(piece.artist.artistid), 1.25, 4.4375, 2.0, 4.625 ) text_into_box ( c, "Piece "+unicode(piece.pieceid), 2.125, 4.4375, 2.875, 4.625 ) text_into_box ( c, piece.artist.artistname(), 1.125, 4.125, 3.875, 4.375 ) text_into_box ( c, piece.name, 0.75, 3.8125, 3.875, 4.0625 ) if piece.not_for_sale: text_into_box ( c, piece.media, 0.875, 3.5, 2.375, 3.75 ) else: text_into_box ( c, piece.media, 0.875, 3.5, 3.875, 3.75 ) text_into_box ( c, piece.not_for_sale and "NFS" or unicode(piece.min_bid), 3.25, 2.625, 3.75, 3.0 ) text_into_box ( c, piece.buy_now and unicode(piece.buy_now) or "N/A", 3.25, 1.9375, 3.75, 2.3125 ) text_into_box ( c, "X", 3.375, 0.375, 3.5625, 0.675, style=left_align_style, fontSize=16 ) c.restoreState () last_artist = piece.artist piece = pieceiter.next () finally: c.showPage () except StopIteration: pass c.save ()
def run(self): try: filename, _ = os.path.splitext(self.data['sourcefile']) folder = os.path.dirname(self.data['sourcefile']) template = PdfReader("template.pdf", decompress=False).pages[0] template_obj = pagexobj(template) with open(self.data['sourcefile'], 'r', newline='') as f: reader = csv.DictReader(f) for n, row in enumerate(reader, 1): fn = f'{filename}-{n}.pdf' outfile = os.path.join(folder, fn) canvas = Canvas(outfile) xobj_name = makerl(canvas, template_obj) canvas.doForm(xobj_name) ystart = 443 # Prepared by canvas.drawString(170, ystart, row.get('name', '')) # Date: Todays date today = datetime.today() canvas.drawString(410, ystart, today.strftime('%F')) # Device/Program Type canvas.drawString(230, ystart-28, row.get('program_type', '')) # Product code canvas.drawString(175, ystart-(2*28), row.get('product_code', '')) # Customer canvas.drawString(315, ystart-(2*28), row.get('customer', '')) # Vendor canvas.drawString(145, ystart-(3*28), row.get('vendor', '')) ystart = 250 # Program Language canvas.drawString(210, ystart, "Python") canvas.drawString(430, ystart, row.get('n_errors', '')) comments = row.get('comments', '').replace('\n', ' ') if comments: lines = textwrap.wrap(comments, width=65) # 45 first_line = lines[0] remainder = ' '.join(lines[1:]) lines = textwrap.wrap(remainder, 75) # 55 lines = lines[:4] # max lines, not including the first. canvas.drawString(155, 223, first_line) for n, l in enumerate(lines, 1): canvas.drawString(80, 223 - (n*28), l) canvas.save() except Exception as e: self.signals.error.emit(str(e)) return self.signals.finished.emit()
def draw(self): c = self.canv titlestyle = ParagraphStyle('Title', fontName='Helvetica', fontSize=36, leading=43) style = ParagraphStyle('Options', leftIndent=10 * mm, firstLineIndent=-10 * mm) text = [Paragraph(self.title, titlestyle)] for field, value in self.options: text.append( Paragraph(u'<b>{}:</b> <i>{}</i>'.format(field, value), style)) f = Frame( 10 * mm, 25 * mm, self.width - 53 * mm, 64 * mm, leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=-5, # -5 font fudge factor showBoundary=0) f.addFromList(text, c) with save_state(c): c.translate(self.width - 40 * mm, self.height - 10 * mm) c.rotate(270) orgstyle = ParagraphStyle('OrgName', fontSize=11, leading=12) style = ParagraphStyle('OrgAddr', fontSize=8, leading=10) f = Frame(0, 0, self.height - 53 * mm, 30 * mm, leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=0, showBoundary=0) l = [] if self.org.name: l.append(Paragraph(self.org.name[0], orgstyle)) if self.org.address: l.append( Paragraph('<br/>'.join(self.org.address[0].split('\n')), style)) if self.org.phone: l.append(Paragraph(self.org.phone[0], style)) f.addFromList(l, c) with save_state(c): c.translate(120 * mm, 15 * mm) c.setFont('Helvetica', 8) c.drawString(0, 0, u'Tickets by ') width = stringWidth(u'Tickets by ', 'Helvetica', 8) with save_state(c): # XXX Ideally, only load the logo once logo = PdfReader( os.path.join(os.path.dirname(__file__), 'eutaxia-logo.pdf')).pages[0] logo = pagexobj(logo) rl_obj = makerl(c, logo) scale = 9 / logo.BBox[3] c.translate(width, -1.5) c.scale(scale, scale) c.doForm(rl_obj) if False: p = c.beginPath() c.setDash(1) p.moveTo(0, 0) p.lineTo(logo.BBox[2], 0) p.lineTo(logo.BBox[2], logo.BBox[3]) p.lineTo(0, logo.BBox[3]) p.close() c.drawPath(p) width += logo.BBox[2] * scale c.drawString(0, -10, u'http://www.eutaxia.se/') width = max(width, stringWidth(u'http://www.eutaxia.se/', 'Helvetica', 8)) c.linkURL('http://www.eutaxia.se', (-1, -13, width, 10), relative=1) bar = code128.Code128(self.barcode, barWidth=0.3 * mm, humanReadable=1) bar.drawOn(c, 10 * mm, 10 * mm) qd = Drawing() # No border, deal with quiet zone manually q = qr.QrCodeWidget(self.qrcode, barLevel='M', barBorder=0, barWidth=30 * mm, barHeight=30 * mm) qd.add(q) renderPDF.draw(qd, c, self.width - q.barWidth - 10 * mm, 10 * mm) c.linkURL(self.qrcode, (self.width - q.barWidth - 10 * mm, 10 * mm, self.width - 10 * mm, 40 * mm), relative=1) p = c.beginPath() c.setDash(1, 2) p.moveTo(0, 0) p.lineTo(self.width, 0) c.drawPath(p) if False: p = c.beginPath() c.setDash(1) p.moveTo(0, 0) p.lineTo(self.width, 0) p.lineTo(self.width, self.height) p.lineTo(0, self.height) p.close() c.drawPath(p)
def draw_card_face(self, c, card_face, domain, colour_scheme, frame_layout, face_nr, x_offset = 0, y_offset = 0): if domain in colour_scheme: colour = (float(colour_scheme[domain][0])/255, float(colour_scheme[domain][1]/255), float(colour_scheme[domain][2]/255)) else: logging.warning('No colour defined for domain: ' + domain + ', in colour scheme.') colour = (0.5, 0.5, 0.5) nr_of_domains = len(self.med_ref_deck.domain_index) this_domain_index = self.med_ref_deck.domain_index.index(domain) # Colour frame c.setFillColorRGB(colour[0], colour[1], colour[2]) if frame_layout['footer_index']: c.roundRect(0 + x_offset, 0 + frame_layout['border']['bottom']*cm * 0.4 + y_offset, frame_layout['card']['width']*cm, frame_layout['card']['height']*cm - frame_layout['border']['bottom']*cm * 0.4, radius=frame_layout['border']['outer_corner_radius']*cm, stroke=0, fill=1) if this_domain_index == 0 and face_nr == 1 or this_domain_index == nr_of_domains-1 and face_nr == 2: c.rect( 0 + x_offset, 0 + frame_layout['border']['bottom']*cm * 0.4 + y_offset, frame_layout['border']['outer_corner_radius']*cm, frame_layout['border']['outer_corner_radius']*cm, stroke=0, fill=1) if this_domain_index == nr_of_domains-1 and face_nr == 1 or this_domain_index == 0 and face_nr == 2: c.rect( frame_layout['border']['left']*cm + frame_layout['content']['width']*cm + frame_layout['border']['right']*cm - frame_layout['border']['outer_corner_radius']*cm + x_offset, 0 + frame_layout['border']['bottom']*cm * 0.4 + y_offset, frame_layout['border']['outer_corner_radius']*cm, frame_layout['border']['outer_corner_radius']*cm, stroke=0, fill=1) else: c.roundRect(0 + x_offset, 0 + y_offset, frame_layout['card']['width']*cm, frame_layout['card']['height']*cm, radius=frame_layout['border']['outer_corner_radius']*cm, stroke=0, fill=1) # Content space c.setFillColorRGB(1, 1, 1) c.roundRect(frame_layout['border']['left']*cm - 0*frame_layout['border']['inner_corner_radius']*cm + x_offset, frame_layout['border']['bottom']*cm - 0*frame_layout['border']['inner_corner_radius']*cm + y_offset, frame_layout['content']['width']*cm + 0*frame_layout['border']['inner_corner_radius']*cm, frame_layout['content']['height']*cm + 0*frame_layout['border']['inner_corner_radius']*cm, radius=frame_layout['border']['inner_corner_radius']*cm, stroke=0, fill=1) # Key ring cut-out: 0 = none, 1 = top left, 2 = top right if face_nr == 1: c.circle(0 + x_offset, frame_layout['card_spread']['height']*cm + y_offset, frame_layout['key_ring']['radius']*cm, stroke=0, fill=1) elif face_nr == 2: if frame_layout['output'] == 'double-sided': c.circle(frame_layout['card']['width']*cm + x_offset, frame_layout['card']['height']*cm + y_offset, frame_layout['key_ring']['radius']*cm, stroke=0, fill=1) else: c.circle(frame_layout['card_spread']['width']*cm, frame_layout['card_spread']['height']*cm + y_offset, frame_layout['key_ring']['radius']*cm, stroke=0, fill=1) # Domain / Caetgory text c.setFont('Helvetica', 10, leading = None) c.drawCentredString(frame_layout['card']['width']*cm/2 + x_offset, frame_layout['card']['height']*cm - 0.48*cm + y_offset, '- ' + xtitle(domain) + ' -') # Header text if len(card_face.header) < 23: c.setFont('Helvetica-Bold', 20, leading = None) elif len(card_face.header) < 36: c.setFont('Helvetica-Bold', 19, leading = None) else: c.setFont('Helvetica-Bold', 18, leading = None) c.drawCentredString(frame_layout['card']['width']*cm/2 + x_offset, frame_layout['card']['height']*cm - 1.2*cm + y_offset, card_face.header) # Footer if frame_layout['footer_index']: width = (frame_layout['border']['left']*cm + frame_layout['content']['width']*cm + frame_layout['border']['right']*cm) / nr_of_domains height = frame_layout['border']['bottom']*cm - frame_layout['border']['inner_corner_radius']*cm x_pos_1 = x_offset + this_domain_index * width x_pos_2 = x_offset + frame_layout['border']['left']*cm + frame_layout['content']['width']*cm + frame_layout['border']['right']*cm - (this_domain_index+1) * width y_pos = 0 + y_offset c.setFillColorRGB(colour[0], colour[1], colour[2]) if face_nr == 1: c.roundRect(x_pos_1, y_pos, width, height, radius=0.06*cm, stroke=0, fill=1) if face_nr == 2: c.roundRect(x_pos_2, y_pos, width, height, radius=0.06*cm, stroke=0, fill=1) else: c.setFillColorRGB(1, 1, 1) c.setFont('Helvetica', 7, leading = None) c.drawCentredString(frame_layout['card']['width']*cm/2 + x_offset, 0.14*cm + y_offset, frame_layout['static_text']['footer']) # Include contents if os.path.isfile(card_face.content_path): c.setFillColorRGB(0, 0, 0) page = pagexobj(PdfReader(card_face.content_path).pages[0]) c.saveState() c.translate(frame_layout['border']['left']*cm + x_offset, frame_layout['border']['bottom']*cm + y_offset) c.doForm(makerl(c, page)) c.restoreState()
def add_bleed(fn, ofn, bleed=None, scale=1.0, crop_marks=None, margin=None): scale = float(scale) pages = PdfReader(fn).pages num_pages = len(pages) pw, ph = get_page_size(pages) page_list = [pagexobj(x) for x in pages] toolboxprint( "Document page size : %4.0f x %4.0f pts ( %4.0f x %4.0f mm) ( %5.2f x %5.2f in)" % (pw, ph, PTS2MM(pw), PTS2MM(ph), PTS2IN(pw), PTS2IN(ph))) w, h = pw * scale, ph * scale if abs(scale - 1.0) > 0: print(crayons.yellow("Rescaling document pages by %.2fx" % (scale))) toolboxprint( "Scaled page size : %4.0f x %4.0f pts ( %4.0f x %4.0f mm) ( %5.2f x %5.2f in)" % (w, h, PTS2MM(w), PTS2MM(h), PTS2IN(w), PTS2IN(h))) doc_style = {"width": w, "height": h} doc = Document(ofn) total_bleed = 0 if bleed is not None: bleed = float(bleed) toolboxprint("Bleed size : %4.0f pts (%4.0f mm) ( %5.3f in)" % (float(bleed), PTS2MM(bleed), PTS2IN(bleed))) total_bleed += float(bleed) if margin is not None: margin = float(margin) toolboxprint("Margin size : %4.0f pts (%4.0f mm) ( %5.3f in)" % (float(margin), PTS2MM(margin), PTS2IN(margin))) total_bleed += float(margin) doc.page_end_callbacks = [] if crop_marks is not None: crop_marks = float(crop_marks) crop_callback = CropMarksCallback(length=crop_marks) crop_callback.style["line-colour"] = (0.5, 0.5, 0.5) doc.page_end_callbacks.append(crop_callback) toolboxprint("Adding crop marks : %4.0f pts (%4.0f mm) ( %5.3f in)" % (crop_marks, PTS2MM(crop_marks), PTS2IN(crop_marks))) doc.set_page_size(doc_style, with_bleed=total_bleed) if total_bleed > 0: wb, hb = doc.bleed_rect.width, doc.bleed_rect.height toolboxprint( "Size with bleed : %4.0f x %4.0f pts ( %4.0f x %4.0f mm) ( %5.2f x %5.2f in)" % (wb, hb, PTS2MM(wb), PTS2MM(hb), PTS2IN(wb), PTS2IN(hb))) doc._doc_start() for idx, page in enumerate(pages): toolboxprint(" Adding page : %3d / %-3d" % (idx + 1, num_pages)) x = 0 y = 0 if total_bleed > 0: x += float(total_bleed) y += float(total_bleed) edges = get_edge_colours(fn, idx, scale) draw_bleed_rect(doc, "top", edges, margin) draw_bleed_rect(doc, "left", edges, margin) draw_bleed_rect(doc, "bottom", edges, margin) draw_bleed_rect(doc, "right", edges, margin) doc.c.saveState() doc.c.translate(x, y) doc.c.scale(scale, scale) doc.c.doForm(makerl(doc.c, page_list[idx])) doc.c.restoreState() if (idx + 1) < num_pages: doc.page_break() doc._doc_end()
input_file = fname + ".pdf" output_file = fname.rstrip("d") + ".pdf" # Get pages reader = PdfReader(input_file) pages = [pagexobj(p) for p in reader.pages] # Compose new pdf canvas = Canvas(output_file) for page_num, page in enumerate(pages, start=1): # Add page canvas.setPageSize((page.BBox[2], page.BBox[3])) canvas.doForm(makerl(canvas, page)) # Draw footer footer_text = "Page %s of %s" % (page_num, len(pages)) x = 128 canvas.saveState() canvas.setStrokeColorRGB(0, 0, 0) canvas.setLineWidth(0.5) canvas.line(66, 53, page.BBox[2] - 66, 53) canvas.setFont("Times-Roman", 10) canvas.drawString(page.BBox[2] - x, 40, footer_text) canvas.restoreState() canvas.showPage()
def combine_pdf(self, files): from reportlab.lib.units import inch print("Hello") merger = PdfFileMerger() for pdf in files: merger.append(pdf) merger.write("/home/jeevan/odoo-11.0/Doc_files/" + "Solution file" + str(datetime.datetime.today().date()) + self.name + ".pdf") merger.close() input_file = "/home/jeevan/odoo-11.0/Doc_files/" + "Solution file" + str( datetime.datetime.today().date()) + self.name + ".pdf" output_file = "/home/jeevan/odoo-11.0/Doc_files/" + "Solution file" + str( datetime.datetime.today().date()) + self.name + ".pdf" reader = PdfReader(input_file) pages = [pagexobj(p) for p in reader.pages] canvas = Canvas(output_file) PAGE_HEIGHT = defaultPageSize[1] PAGE_WIDTH = defaultPageSize[0] Title = "Veeraja Industries Pvt Ltd." Title1 = "Date:" + self.date_order + " " + "Proposal No:" + self.name + " " + "Revision:" + ' ' for page_num, page in enumerate(pages, start=1): # Add page canvas.setPageSize((page.BBox[2], page.BBox[3])) canvas.doForm(makerl(canvas, page)) # Draw footer footer_text = "Page %s of %s" % (page_num, len(pages)) x = 128 canvas.saveState() canvas.setFillColorRGB(1, 0, 0) canvas.drawCentredString(PAGE_WIDTH / 2.0, PAGE_HEIGHT - 50, Title) canvas.setFillColorRGB(1, 0, 0) canvas.drawCentredString(PAGE_WIDTH / 2.1, PAGE_HEIGHT - 70, Title1) # canvas.setFillColorRGB(255,255,0) # canvas.rect(1*inch,10.6*inch,6*inch,0.3*inch, fill=1) canvas.setFont('Times-Roman', 9) canvas.setStrokeColorRGB(0, 0, 0) canvas.setFont('Times-Roman', 10) canvas.drawCentredString(page.BBox[2] - x, 80, footer_text) canvas.restoreState() canvas.showPage() canvas.save() for top, dirs, files in os.walk('/home/jeevan/odoo-11.0/Doc_files/'): for filename in files: if filename.endswith('.pdf'): abspath = os.path.join(top, filename) subprocess.call( 'lowriter --invisible --convert-to docx "{}"'.format( abspath), shell=True) print("Convert Done") with open(output_file, "rb") as f: document = f.read() self.converted_doc_file = base64.b64encode(document) self.filename = "Final Solution file" + str( datetime.datetime.today().date()) + "_" + self.name + ".pdf" os.remove("/home/jeevan/odoo-11.0/Doc_files/" + "Solution file" + str(datetime.datetime.today().date()) + self.name + ".pdf")
def create_card_face(c, domain, category, header_text, footer_text, frame_colour, content_pdf_fn, offset=0, key_ring=1): # Colour frame c.setFillColorRGB(frame_colour[0], frame_colour[1], frame_colour[2]) c.roundRect(0 + offset, 0, FACE_DIM[0], FACE_DIM[1], radius=OUTER_ROUNDED_RAD, stroke=0, fill=1) # Content space c.setFillColorRGB(1, 1, 1) c.roundRect(FACE_MARGINS[3] + offset, FACE_MARGINS[2], CONTENT_DIM[0], CONTENT_DIM[1], radius=INNER_ROUNDED_RAD, stroke=0, fill=1) # Key ring cut-out, 0 = none, 1 = left, 2 = right if key_ring == 1: c.circle(0, DOCUMENT_DIM[1], KEY_RING_RAD, stroke=0, fill=1) elif key_ring == 2: c.circle(DOCUMENT_DIM[0], DOCUMENT_DIM[1], KEY_RING_RAD, stroke=0, fill=1) # Domain / Caetgory text c.setFont('Helvetica', 10, leading=None) c.drawCentredString(FACE_DIM[0] / 2 + offset, FACE_DIM[1] - 0.47 * cm, '- ' + domain.title() + ' -') # c.drawCentredString(FACE_DIM[0]/2 + offset, FACE_DIM[1] - 0.47*cm, domain.title() + ' / ' + category.title()) # Header text c.setFont('Helvetica-Bold', 20, leading=None) c.drawCentredString(FACE_DIM[0] / 2 + offset, FACE_DIM[1] - 1.23 * cm, header_text) # Footer text c.setFont('Helvetica', 8, leading=None) c.drawCentredString(FACE_DIM[0] / 2 + offset, 0.15 * cm, footer_text) # Include contents c.setFillColorRGB(0, 0, 0) page = pagexobj(PdfReader(content_pdf_fn).pages[0]) c.saveState() c.translate(FACE_MARGINS[3] + offset, FACE_MARGINS[2]) c.doForm(makerl(c, page)) c.restoreState()
def _create_pdfs(self): total_pg_num = 2 for report in self.selected_reports: canvas = Canvas(report.pdf_path) if self.create_print_file: canvas_print = Canvas(report.print_path) for pg_num, pg in enumerate(report.pdf_pages, start=1): canvas.setPageSize((pg.BBox[2], pg.BBox[3])) canvas.doForm(makerl(canvas, pg)) if self.create_print_file: canvas_print.setPageSize((pg.BBox[2], pg.BBox[3])) canvas_print.doForm(makerl(canvas_print, pg)) if report.id != self.check_files_ids['cover']: footer = f'Page {total_pg_num} of {self.total_pages}' canvas.saveState() canvas.setFont('Calibri', 12) canvas.drawCentredString(pg.BBox[2]//2, 15, footer) canvas.restoreState() if self.create_print_file: canvas_print.saveState() canvas_print.setFont('Calibri', 12) canvas_print.drawCentredString(pg.BBox[2]//2, 15, footer) canvas_print.restoreState() total_pg_num += 1 canvas.showPage() if self.create_print_file: canvas_print.showPage() # if the print file is being created and the report is # doubled sided and it's not the last page or its the last # page of the report and the report is double sided and # that report has an odd number of pages then a blank page # is inserted after this page to allow for mixed single and # double sided printing when printing the document in double sided mode if self.create_print_file: if ( (not report.is_duplex and total_pg_num <= self.total_pages) or ( pg_num == len(report.pdf_pages) and report.is_duplex and len(report.pdf_pages) % 2 != 0 ) ): # inserts the blank page canvas_print.setPageSize((pg.BBox[2], pg.BBox[3])) canvas_print.doForm( makerl(canvas_print, self.blank_pdf_page)) canvas_print.showPage() canvas.save() if self.create_print_file: canvas_print.save()
def draw_card_face(self, c, card_face, domain, colour_scheme, frame_layout, page_nr, offset=0): colour = colour_scheme[domain] # Colour frame c.setFillColorRGB(colour[0], colour[1], colour[2]) c.roundRect(0 + offset, 0, frame_layout['card']['width'] * cm, frame_layout['card']['height'] * cm, radius=frame_layout['border']['outer_corner_radius'] * cm, stroke=0, fill=1) # Content space c.setFillColorRGB(1, 1, 1) c.roundRect(frame_layout['border']['left'] * cm + offset, frame_layout['border']['bottom'] * cm, frame_layout['content']['width'] * cm, frame_layout['content']['height'] * cm, radius=frame_layout['border']['inner_corner_radius'] * cm, stroke=0, fill=1) # Key ring cut-out: 0 = none, 1 = top left, 2 = top right if page_nr == 1: c.circle(0, frame_layout['card_spread']['height'] * cm, frame_layout['key_ring']['radius'] * cm, stroke=0, fill=1) elif page_nr == 2: c.circle(frame_layout['card_spread']['width'] * cm, frame_layout['card_spread']['height'] * cm, frame_layout['key_ring']['radius'] * cm, stroke=0, fill=1) # Domain / Caetgory text c.setFont('Helvetica', 10, leading=None) c.drawCentredString(frame_layout['card']['width'] * cm / 2 + offset, frame_layout['card']['height'] * cm - 0.47 * cm, '- ' + domain.title() + ' -') # Header text c.setFont('Helvetica-Bold', 20, leading=None) c.drawCentredString(frame_layout['card']['width'] * cm / 2 + offset, frame_layout['card']['height'] * cm - 1.23 * cm, card_face.header) # Footer text c.setFont('Helvetica', 8, leading=None) c.drawCentredString(frame_layout['card']['width'] * cm / 2 + offset, 0.15 * cm, frame_layout['static_text']['footer']) # Include contents c.setFillColorRGB(0, 0, 0) page = pagexobj(PdfReader(card_face.content_path).pages[0]) c.saveState() c.translate(frame_layout['border']['left'] * cm + offset, frame_layout['border']['bottom'] * cm) c.doForm(makerl(c, page)) c.restoreState()
# Eliminar esto cuando se cargue estos datos del excell cliente = 'Quala' aspecto = 'Cumple' color = 'Cumple' olor = 'Cumple' sp_fases = 'Cumple' atr_calidad = 'Cumple' # Una vez obtenido los valores se imprimen el el pdf con el siguiente código created_pdf_name = saved_coa_path + referencia + lote + '.pdf' c = canvas.Canvas(created_pdf_name) template = PdfReader(files_path + pdf_template_file_name, decompress=False).pages t = pagexobj(template[0]) c.doForm(makerl(c, t)) c.setFillColor(blue) c.drawString(1.8 * inch, 8.92 * inch, cliente) c.drawString(2.42 * inch, 8.72 * inch, 'COA-No-' + coa_number) c.drawString(2.06 * inch, 8.51 * inch, referencia) c.drawString(1.60 * inch, 8.32 * inch, lote) c.drawString(2.84 * inch, 8.12 * inch, fecha_elab) c.drawString(2.75 * inch, 7.92 * inch, fecha_exp) c.drawString(2.50 * inch, 7.71 * inch, str(cant_cajas)) c.drawString(2.60 * inch, 7.52 * inch, und_caja) c.drawString(2.58 * inch, 7.31 * inch, str(total_und)) c.drawString(6.23 * inch, 6.61 * inch, aspecto) c.drawString(6.23 * inch, 6.25 * inch, color) c.drawString(6.23 * inch, 6.06 * inch, olor) c.drawString(6.23 * inch, 5.83 * inch, str(pH)) c.drawString(6.23 * inch, 5.63 * inch, str(viscosidad))
def file_x(route): input_file = route output_file = route.replace("static","static_pdf") print input_file # Get pages reader = PdfReader(input_file) pages = [pagexobj(p) for p in reader.pages] # Compose new pdf canvas = Canvas(output_file) for page_num, page in enumerate(pages, start=1): # Add page canvas.setPageSize((page.BBox[2], page.BBox[3])) canvas.doForm(makerl(canvas, page)) # Draw footer footer_text = "Descargado desde https://UdpCursos.com" x = 180 canvas.saveState() canvas.setFont('Times-Roman', 10) canvas.drawString(page.BBox[2]-x, 40, footer_text) canvas.restoreState() canvas.showPage() canvas.save()