def add_footer(input_file, output_file): logging.info("add_footer started") # Get pages reader = PdfReader("%s.pdf" % (input_file)) pages = [pagexobj(p) for p in reader.pages] # Compose new pdf canvas = Canvas("%s.pdf" % (output_file)) pdfmetrics.registerFont( TTFont('SourceSansPro', 'SourceSansPro-Regular.ttf')) 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 = "www.borderviolence.eu" x = 80 canvas.saveState() canvas.setStrokeColorRGB(0.19, 0.19, 0.19) canvas.setLineWidth(0.3) canvas.line(75, 78, page.BBox[2] - 66, 78) canvas.setFont('SourceSansPro', 10) canvas.setFillColor(HexColor(0x333333)) canvas.drawString(page.BBox[2] - x, 85, str(page_num)) canvas.drawString(page.BBox[2] - x - 436, 85, footer_text) canvas.restoreState() canvas.showPage() canvas.save() logging.info("PDF with footer %s.pdf was saved" % (output_file)) return 1
def edit_pdf(filePath): input_file = filePath output_file = filePath # 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: 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', 10) canvas.drawString(page.BBox[1] +x, 30, footer_text) canvas.restoreState() 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 add_footer(): input_file = "/tmp/merged.pdf" output_file = "/tmp/merged_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)) canvas.setFont("Helvetica", 10) if canvas._pagesize[0] > canvas._pagesize[1]: canvas.saveState() canvas.rotate(270) canvas.translate(-30, -A4[0] + 30) canvas.drawRightString( -10, A4[0], "%d de %d" % (canvas._pageNumber, len(pages))) canvas.restoreState() else: canvas.drawRightString( A4[0] - 60, 30, "%d de %d" % (canvas._pageNumber, len(pages))) canvas.showPage() canvas.save()
def include_footer(input_file_path, output_file_path, link=None): # Get pages reader = PdfReader(input_file_path) pages = [pagexobj(p) for p in reader.pages] # Compose new pdf canvas = Canvas(output_file_path) 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 = f"This report is reproducible with FAIR data. Find the source datasets here: {link}" x = 80 canvas.saveState() canvas.setStrokeColorRGB(0, 0, 0) canvas.setLineWidth(0.5) canvas.line(66, 40, page.BBox[2] - 66, 40) canvas.setFont('Helvetica', 8) canvas.drawString(66, 25, footer_text) canvas.linkURL(link, (66, 25, page.BBox[2] - 66, 40)) canvas.restoreState() canvas.showPage() canvas.save()
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 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 pdf_insert_doi_using_pdfrw(req_content, doi): input_file = io.BytesIO(req_content) pdf_buffer = io.BytesIO() reader = PdfReader(input_file) pages = [pagexobj(p) for p in reader.pages] canvas = Canvas(pdf_buffer) for page_num, page in enumerate(pages, start=1): canvas.setPageSize((page.BBox[2], page.BBox[3])) canvas.doForm(makerl(canvas, page)) # Draw footer if page_num == 1: footer_text = "https://doi.org/{}".format(doi) canvas.saveState() canvas.setFont("Helvetica-Bold", 8) canvas.setFillColor(HexColor('#990100')) canvas.drawCentredString(page.BBox[2] / 2, 20, footer_text) canvas.restoreState() canvas.showPage() canvas.save() pdf_bytes = pdf_buffer.getbuffer() return pdf_bytes
def _make_cover(self): name = f'{self.jurisdiction.id}_packet_cover.pdf' path = str(constants.TEMP_FILE_PATH.joinpath(name)) reader = PdfReader(self.blank_cover_path) page = pagexobj(reader.pages[0]) canvas = Canvas(path, pagesize=letter) canvas.setPageSize((page.BBox[2], page.BBox[3])) canvas.doForm(makerl(canvas, page)) canvas.saveState() max_title_len = 15 max_title_font_size = 60 max_title_pixel = max_title_len * max_title_font_size x = 15 mid_x = x//2 y1 = 15 fs1 = 16 y2 = y1 + mid_x + fs1 fs2 = 36 y3 = y2 + mid_x + fs2 fs3 = max_title_font_size title = self.jurisdiction.name rep_info = self._get_rep_info() # draws the email and phone of the rep canvas.setFontSize(fs1) canvas.setFillGray(0.45) canvas.drawString(x=x, y=y1, text=f'{rep_info[0]} | {rep_info[1]}') canvas.setFont('Calibri', fs2) canvas.drawString( x=x, y=y2, text=f'Economic Review {self.selections.period}') canvas.setFillColorRGB(0, .23, .34) if len(title) > max_title_len: fs3 = max_title_pixel//len(title) canvas.setFontSize(fs3) canvas.drawString(x=x, y=y3, text=title) canvas.restoreState() canvas.showPage() canvas.save() self._set_path(self.check_files_ids['cover'], path)
def add_page_number( pdf_name, source_data_footext=ReportParameters.REFERENCE_DATA_TEXT, reference_footer_text=ReportParameters.REFERENCE_USE_FOOTER_TEXT): """ Args: pdf_name: source_data_footext: reference_footer_text: Returns: """ 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)) # Draw footer page_number_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, 72, page.BBox[2] - 66, 72) canvas.setFont('Times-Roman', 10) canvas.drawString(x=(page.BBox[2] - x), y=60, text=page_number_footer_text) canvas.drawString(x=66, y=60, text=source_data_footext) canvas.drawString(x=66, y=45, text=reference_footer_text) canvas.restoreState() canvas.showPage() # Save pdf canvas.save()
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, decompress=False).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 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 go(inpfn, firstpage, lastpage): firstpage, lastpage = int(firstpage), int(lastpage) outfn = 'subset.' + 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((page.BBox[2], page.BBox[3])) canvas.doForm(makerl(canvas, page)) canvas.showPage() canvas.save()
def encryptPdfInMemory(inputPDF, userPassword, ownerPassword=None, canPrint=1, canModify=1, canCopy=1, canAnnotate=1, strength=40): """accepts a PDF file 'as a byte array in memory'; return encrypted one. This is a high level convenience and does not touch the hard disk in any way. If you are encrypting the same file over and over again, it's better to use pageCatcher and cache the results.""" try: from rlextra.pageCatcher.pageCatcher import storeFormsInMemory, restoreFormsInMemory except ImportError: raise ImportError( '''reportlab.lib.pdfencrypt.encryptPdfInMemory failed because rlextra cannot be imported. See https://www.reportlab.com/downloads''') (bboxInfo, pickledForms) = storeFormsInMemory(inputPDF, all=1, BBoxes=1) names = list(bboxInfo.keys()) firstPageSize = bboxInfo['PageForms0'][2:] #now make a new PDF document buf = getBytesIO() canv = Canvas(buf, pagesize=firstPageSize) # set a standard ID while debugging if CLOBBERID: canv._doc._ID = "[(xxxxxxxxxxxxxxxx)(xxxxxxxxxxxxxxxx)]" formNames = restoreFormsInMemory(pickledForms, canv) for formName in formNames: canv.setPageSize(bboxInfo[formName][2:]) canv.doForm(formName) canv.showPage() encryptCanvas(canv, userPassword, ownerPassword, canPrint, canModify, canCopy, canAnnotate, strength=strength) canv.save() return buf.getvalue()
def split(path, number_of_pages, output): pdf_obj = PdfReader(path) my_canvas = Canvas(output) # create page objects pages = pdf_obj.pages[0:number_of_pages] pages = [pagexobj(page) for page in pages] for page in pages: my_canvas.setPageSize((page.BBox[2], page.BBox[3])) my_canvas.doForm(makerl(my_canvas, page)) my_canvas.showPage() # write the new PDF to disk my_canvas.save()
def run(self): try: outfile = "result.pdf" template = PdfReader("template.pdf", decompress=False).pages[0] template_obj = pagexobj(template) canvas = Canvas(outfile) xobj_name = makerl(canvas, template_obj) canvas.doForm(xobj_name) canvas.drawString(230, 610, self.data['totalTickets']) canvas.drawString(240, 576, self.data['serviceTickets']) canvas.drawString(250, 545, self.data['incidentTickets']) canvas.drawString(275, 512, self.data['unassignedTickets']) canvas.drawString(89, 457, self.data['reasonOne']) canvas.drawString(89, 430, self.data['reasonTwo']) canvas.drawString(89, 406, self.data['reasonThree']) additionalNotes = self.data['additionalNotes'].replace('\n', ' ') if additionalNotes: lines = textwrap.wrap(additionalNotes, width=55) first_line = lines[0] remainder = ' '.join(lines[1:]) lines = textwrap.wrap(remainder, 50) # 55 lines = lines[:3] # max lines, not including the first. canvas.drawString(170, 375, first_line) for n, l in enumerate(lines, 1): canvas.drawString(71, 350, l) canvas.save() except Exception as e: self.signals.error.emit(str(e)) return self.signals.file_saved_as.emit(outfile)
def generate_pdf(self): pathlib.Path(settings.BASE_DIR + settings.MEDIA_URL + 'factors').mkdir( parents=True, exist_ok=True) fn = str(uuid.uuid1()) + ".pdf" outfile = '/home/hpc/HPCPortal/media/factors/{}'.format( fn) # output file name file_path = 'media/factors/{}'.format(fn) template = PdfReader("/home/hpc/HPCPortal/template.pdf", decompress=False).pages[0] # read template pdf template_obj = pagexobj(template) canvas = Canvas(outfile) xobj_name = makerl(canvas, template_obj) canvas.doForm(xobj_name) pdfmetrics.registerFont( TTFont( 'BNazanin', '/home/hpc/HPCPortal/mainapp/static/mainapp/fonts/B Nazanin Bold_YasDL.com.ttf' )) canvas.setFont( 'BNazanin', 14) # set font family and size to detect persian letters full_name = arabic_reshaper.reshape(u'{}'.format( self.cleaned_data['user'].get_full_name())) full_name = get_display(full_name) today = timezone.localdate(timezone.now()) canvas.drawString( 21, 786, gregorian_to_jalali(today).strftime("%Y/%m/%d")) # header date canvas.drawString(315, 518, f'{self.get_total_payments():,}') # total payment canvas.drawString(375, 498, full_name) # full name canvas.drawString( 180, 518, gregorian_to_jalali( self.cleaned_data['start_date']).strftime("%Y/%m/%d")) # from canvas.drawString( 80, 518, gregorian_to_jalali( self.cleaned_data['end_date']).strftime("%Y/%m/%d")) # to canvas.save() return file_path
def __set_page_number(self, path_report): try: reader = PdfReader(path_report) pages = [pagexobj(p) for p in reader.pages] canvas = Canvas(path_report) 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_main = "ENGIE BRASIL ENERGIA S.A." footer_text_address = "Rua Paschoal Apóstolo Pítsica, 5064 - 88025-255 - Florianópolis - Santa Catarina - Brasil" footer_text_page = "Página %s de %s" % (page_num, len(pages)) x1 = 75 x2 = 360 x3 = 480 canvas.saveState() header_text = self.__build_title_subtitle() f = Frame(inch, inch, 6.26*inch, 10.5*inch) f.addFromList(header_text,canvas) canvas.setFont('Times-Roman', 8) canvas.drawString(page.BBox[2]-x2, 30, footer_text_main) canvas.drawString(page.BBox[2]-x3, 15, footer_text_address) canvas.drawString(page.BBox[2]-x1, 15, footer_text_page) canvas.restoreState() canvas.showPage() canvas.save() except Exception as ex: print(ex) arcpy.AddMessage(ex.message)
def SetHeaderFooter(inputFile, outputFile, logoFile): try: ## Read Pdf reader = PdfReader(inputFile) pages = [pagexobj(p) for p in reader.pages] ## Total Pages # compose new pdf canvas = Canvas(outputFile) 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-Footer footer_text = "It’s easy to play any musical instrument:" footer_text1 = "all you have to do is touch the right key at the right time and the instrument will play itself." header_text = "Jhon institute" x = 540 y = 50 hw = 120 ## Canvas properties canvas.saveState() canvas.setStrokeColorRGB(0, 0, 0) canvas.setLineWidth(0.5) canvas.setFont('Helvetica-Bold', 11) canvas.drawString(page.BBox[2] - x, 35, footer_text) canvas.drawString(page.BBox[2] - x, 20, footer_text1) canvas.drawString(page.BBox[2] - 150, page.BBox[3] - y, header_text) canvas.drawImage(logoFile, page.BBox[2] - x, page.BBox[3] - 100, width=hw, height=hw, preserveAspectRatio=True) canvas.restoreState() canvas.showPage() canvas.save() return True except: return False
def encryptPdfInMemory(inputPDF, userPassword, ownerPassword=None, canPrint=1, canModify=1, canCopy=1, canAnnotate=1, strength=40): """accepts a PDF file 'as a byte array in memory'; return encrypted one. This is a high level convenience and does not touch the hard disk in any way. If you are encrypting the same file over and over again, it's better to use pageCatcher and cache the results.""" try: from rlextra.pageCatcher.pageCatcher import storeFormsInMemory, restoreFormsInMemory except ImportError: raise ImportError('''reportlab.lib.pdfencrypt.encryptPdfInMemory failed because rlextra cannot be imported. See http://developer.reportlab.com''') (bboxInfo, pickledForms) = storeFormsInMemory(inputPDF, all=1, BBoxes=1) names = bboxInfo.keys() firstPageSize = bboxInfo['PageForms0'][2:] #now make a new PDF document buf = getStringIO() canv = Canvas(buf, pagesize=firstPageSize) # set a standard ID while debugging if CLOBBERID: canv._doc._ID = "[(xxxxxxxxxxxxxxxx)(xxxxxxxxxxxxxxxx)]" encryptCanvas(canv, userPassword, ownerPassword, canPrint, canModify, canCopy, canAnnotate, strength=strength) formNames = restoreFormsInMemory(pickledForms, canv) for formName in formNames: #need to extract page size in future canv.doForm(formName) canv.showPage() canv.save() return buf.getvalue()
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 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 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 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_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()
class Report(object): def __init__(self, pdf_file=None): self.pdf_file = pdf_file self.title = 'Untitled Report' self.author = 'Podunk' self.page_width, self.page_height = paper.LETTER_PORTRAIT self.left_margin = 54 self.top_margin = 72 self.right_margin = 54 self.bottom_margin = 72 ## Metrics self._top_edge = self.page_height - 1 self._right_edge = self.page_width - 1 self._bottom_edge = 0 self._left_edge = 0 self._working_width = self.page_width - ( self.right_margin + self.left_margin ) self._working_height = self.page_height - ( self.top_margin + self.bottom_margin ) ## Create the ReportLab Canvas self.canvas = Canvas(self.pdf_file, pagesize = (self.page_width, self.page_height)) ## Create the page header self.header = Field() self.header.box.bottom_border = 2 self.header.box.line_cap = 1 #self.header.box.border_color = (.6,.6,.6) self.header.style.vertical_padding = 6 self.header.style.bold = True self.header.style.size = 10 #self.header.style.color = (.6,.6,.6) self.header.style.horizontal_alignment = alignment.RIGHT self.header.width = self._working_width ## Create the page footer self.footer = Field() self.footer.box.top_border = 1 self.footer.box.line_cap = 1 #self.footer.box.border_color = (.6,.6,.6) self.footer.style.horizontal_alignment = alignment.CENTER self.footer.style.vertical_alignment = alignment.TOP #self.footer.style.color = (.6,.6,.6) self.footer.width = self._working_width self.footer.style.size = 8 ## Create the date label self.date = Field(datetime.datetime.today()) self.date.format = format_report_date self.date.style.vertical_alignment = alignment.TOP #self.date.style.color = (.6,.6,.6) #self.date.style.horizontal_padding = 0 self.date.style.size = 8 ## Create the page number label; 'Page X of' self.page_num = Field() self.page_num.style.horizontal_alignment = alignment.RIGHT self.page_num.style.vertical_alignment = alignment.TOP self.page_num.width = self._working_width - 13 #self.page_num.style.color = (.6,.6,.6) self.page_num.horizontal_padding = 0 self.page_num.style.size = 8 ## Create the last page number label self.last_page = Field() #self.last_page.style.horizontal_alignment = alignment.LEFT self.last_page.style.vertical_alignment = alignment.TOP #self.last_page.width = self._working_width #self.last_page.style.color = (.6,.6,.6) self.last_page.horizontal_padding = 0 self.last_page.style.size = 8 ## Objects to be drawn self.draw_list = [] self._page_count = 1 #-----------------------------------------------------------------------Add def add(self, item): ## Add any object that, duck-typingly, has a 'draw_some' method self.draw_list.append(item) #--------------------------------------------------------------------Create def create(self): self.canvas.setAuthor(self.author) self.canvas.setTitle(self.title) self.canvas.setSubject('Python Generated Report') self._draw_header() self._draw_footer() vspace = self._working_height left = self.left_margin right = self.page_width - self.right_margin for item in self.draw_list: while True: if vspace < 1: self._start_new_page() vspace = self._working_height yoff = self.bottom_margin + vspace used = item.draw_some(self.canvas, left, right, yoff, vspace) if used == 0: break else: vspace -= used ## Add the numbering for last page ## We have to do this as a PDF 'Form' object since we don't know in ## advance how many pages there will be. self.canvas.beginForm('last_page') self.canvas.saveState() self.last_page.value = '%d' % self._page_count self.last_page.draw(self.canvas, self._right_edge - ( self.right_margin + 14), self.bottom_margin * .65) self.canvas.restoreState() self.canvas.endForm() ## Close the PDF self.canvas.save() #----------------------------------------------------------------Start Page def _start_new_page(self): self._page_count += 1 self.canvas.showPage() self._draw_header() self._draw_footer() #---------------------------------------------------------------Draw Header def _draw_header(self): self.header.value = self.title self.header.draw(self.canvas, self.left_margin, self._top_edge - (self.top_margin * .65) ) #---------------------------------------------------------------Draw Footer def _draw_footer(self): self.footer.value = self.author self.footer.draw(self.canvas, self.left_margin, self.bottom_margin * .65) self.date.draw(self.canvas, self.left_margin, self.bottom_margin * .65) self.page_num.value = 'Page %d of ' % self._page_count self.page_num.draw(self.canvas, self.left_margin, self.bottom_margin * .65) self.canvas.doForm('last_page')
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 ()
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()
class Report(object): def __init__(self, pdf_file=None, paper_type=None, time_zone=None, left_margin=None, top_margin=None, right_margin=None, bottom_margin=None, date_flag=None, flag_footer=None, logo=None, logo_filename=None, logo_width=None, logo_height=None, logo_top_margin=None): self.pdf_file = pdf_file self.title = '' self.author = 'Manexware S.A.' self.department = 'OpenEduNav' self.date_flag = date_flag self.logo = logo self.logo_filename = logo_filename self.logo_width = logo_width self.logo_height = logo_height self.flag_footer = flag_footer if time_zone: local_tz = pytz.timezone(time_zone) else: local_tz = pytz.timezone('America/Guayaquil') utc_dt = datetime.datetime.utcnow() local_dt = utc_dt.replace(tzinfo=pytz.utc).astimezone(local_tz) date_time = local_tz.normalize(local_dt) if paper_type: self.page_width, self.page_height = paper_type else: self.page_width, self.page_height = paper.A4_LANDSCAPE if left_margin is not None: self.left_margin = left_margin else: self.left_margin = 50 if top_margin is not None: self.top_margin = top_margin else: self.top_margin = 40 if right_margin is not None: self.right_margin = right_margin else: self.right_margin = 50 if bottom_margin is not None: self.bottom_margin = bottom_margin else: self.bottom_margin = 40 if logo_top_margin is not None: self.logo_top_margin = logo_top_margin else: self.logo_top_margin = 70 # Metrics self._top_edge = self.page_height - 1 self._right_edge = self.page_width - 1 self._bottom_edge = 0 self._left_edge = 0 self._working_width = self.page_width - (self.right_margin + self.left_margin) self._working_height = self.page_height - (self.top_margin + self.bottom_margin) # Create the ReportLab Canvas self.canvas = Canvas(self.pdf_file, pagesize=(self.page_width, self.page_height)) # Create the page header self.header = Field() # self.header.box.bottom_border = 2 # self.header.box.line_cap = 1 # self.header.box.border_color = (.6,.6,.6) self.header.style.vertical_padding = 6 self.header.style.bold = True self.header.style.size = 10 # self.header.style.color = (.6,.6,.6) self.header.style.horizontal_alignment = alignment.RIGHT self.header.width = self._working_width # Create the page footer self.footer = Field() self.footer.box.top_border = 1 self.footer.box.line_cap = 1 # self.footer.box.border_color = (.6,.6,.6) self.footer.style.horizontal_alignment = alignment.CENTER self.footer.style.vertical_alignment = alignment.TOP # self.footer.style.color = (.6,.6,.6) self.footer.width = self._working_width self.footer.style.size = 8 # Create the date label self.date = Field(date_time) self.date.format = format_report_date self.date.style.vertical_alignment = alignment.TOP # self.date.style.color = (.6,.6,.6) # self.date.style.horizontal_padding = 0 self.date.style.size = 9 # Create the department label self.departmentField = Field() self.departmentField.style.vertical_alignment = alignment.TOP # self.date.style.color = (.6,.6,.6) # self.date.style.horizontal_padding = 0 self.departmentField.style.size = 8 # Create the page number label; 'Page X of' self.page_num = Field() self.page_num.style.horizontal_alignment = alignment.RIGHT self.page_num.style.vertical_alignment = alignment.TOP self.page_num.width = self._working_width - 13 # self.page_num.style.color = (.6,.6,.6) self.page_num.horizontal_padding = 0 self.page_num.style.size = 8 # Create the last page number label self.last_page = Field() # self.last_page.style.horizontal_alignment = alignment.LEFT self.last_page.style.vertical_alignment = alignment.TOP # self.last_page.width = self._working_width # self.last_page.style.color = (.6,.6,.6) self.last_page.horizontal_padding = 0 self.last_page.style.size = 8 # Objects to be drawn self.draw_list = [] self._page_count = 1 # -----------------------------------------------------------------------Add def add(self, item): # Add any object that, duck-typingly, has a 'draw_some' method self.draw_list.append(item) # --------------------------------------------------------------------Create def create(self): self.canvas.setAuthor(self.author) self.canvas.setTitle(self.title) self.canvas.setSubject('Python Generated Report') self._draw_header() if self.flag_footer: self._draw_footer() vspace = self._working_height left = self.left_margin right = self.page_width - self.right_margin if self.logo: self._draw_logo() vspace = self._working_height - self.logo_height for item in self.draw_list: while True: if vspace < 1: self._start_new_page() if self.logo: vspace = self._working_height - self.logo_height else: vspace = self._working_height yoff = self.bottom_margin + vspace used = item.draw_some(self.canvas, left, right, yoff, vspace) if used == 0: break else: vspace -= used # Add the numbering for last page # We have to do this as a PDF 'Form' object since we don't know in # advance how many pages there will be. self.canvas.beginForm('last_page') self.canvas.saveState() self.last_page.value = '%d' % self._page_count self.last_page.draw(self.canvas, self._right_edge - (self.right_margin + 14), self.bottom_margin * .65) self.canvas.restoreState() self.canvas.endForm() # Close the PDF self.canvas.save() # ----------------------------------------------------------------Start Page def _start_new_page(self): self._page_count += 1 self.canvas.showPage() # self.canvas.doForm('page %s' % self._page_count) self._draw_header() if self.flag_footer: self._draw_footer() if self.logo: self._draw_logo() # ---------------------------------------------------------------Draw Header def _draw_header(self): self.header.value = self.title self.header.draw(self.canvas, self.left_margin, self._top_edge - (self.top_margin * .65)) if self.date_flag: self.date.draw(self.canvas, self._right_edge - 200, self._top_edge - (self.top_margin * .65)) # ---------------------------------------------------------------Draw Logo def _draw_logo(self): if self.logo: x = ((self.page_width - self.logo_width) / 2) y = self._top_edge - self.logo_top_margin self.canvas.drawImage(self.logo_filename, x, y, self.logo_width, self.logo_height) # ---------------------------------------------------------------Draw Footer def _draw_footer(self): self.footer.value = self.author self.footer.draw(self.canvas, self.left_margin, self.bottom_margin * .65) self.departmentField.value = self.department self.departmentField.draw(self.canvas, self.left_margin, self.bottom_margin * .65) self.page_num.value = 'Página No. %d de ' % self._page_count self.page_num.draw(self.canvas, self.left_margin, self.bottom_margin * .65) self.canvas.doForm('last_page')
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 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 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()