Python reportlab.lib.pagesizes.letter() Examples

The following are 26 code examples of reportlab.lib.pagesizes.letter(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module reportlab.lib.pagesizes , or try the search function .
Example #1
Source File: generic_pdf.py    From multiscanner with Mozilla Public License 2.0 7 votes vote down vote up
def __init__(self, pdf_components):
        self.style = getSampleStyleSheet()
        self.style['Normal'].leading = 16
        self.style.add(ParagraphStyle(name='centered', alignment=TA_CENTER))
        self.style.add(ParagraphStyle(name='centered_wide', alignment=TA_CENTER,
                                      leading=18))
        self.style.add(ParagraphStyle(name='section_body',
                                      parent=self.style['Normal'],
                                      spaceAfter=inch * .05,
                                      fontSize=11))
        self.style.add(ParagraphStyle(name='bullet_list',
                                      parent=self.style['Normal'],
                                      fontSize=11))
        if six.PY3:
            self.buffer = six.BytesIO()
        else:
            self.buffer = six.StringIO()
        self.firstPage = True
        self.document = SimpleDocTemplate(self.buffer, pagesize=letter,
                                          rightMargin=12.7 * mm, leftMargin=12.7 * mm,
                                          topMargin=120, bottomMargin=80)

        self.tlp_color = pdf_components.get('tlp_color', '')
        self.pdf_components = pdf_components
        self.pdf_list = [] 
Example #2
Source File: PlotDecomposition_SBS1536.py    From SigProfilerExtractor with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def gen_decomposition(denovo_name, basis_names, weights, output_path, project, reconstruction, statistics):
	# Note: 0th index contains the title of the column
	c = canvas.Canvas(output_path+"/"+denovo_name+"_decomposition_"+project+".pdf", pagesize=letter)
	c.setPageSize(landscape(letter))
	c.setFont("Arial-Bold", 7.19)

	basis_plots = []
	for i in range(0,len(basis_names)):
		basis_plots.append([basis_names[i], weights[i]])

	# create for loop to iterate through list, then change second value in list of lists
	# Otherwise sorts strings and then 5.14% > 48.54%
	for j in range(0, len(basis_names)):
		basis_plots[j][1] = float(basis_plots[j][1].strip("%"))
	sorted_list = sorted(basis_plots, key=lambda tup: tup[1], reverse=True)

	gen_plot(denovo_name, sorted_list, output_path, project, c, reconstruction, statistics)

	c.save() 
Example #3
Source File: builder.py    From tia with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def onPage(self, canvas, doc):
        c = canvas
        w, h = c._pagesize
        # The cover page just has some drawing on the canvas.
        c.saveState()
        isletter = (w, h) == letter
        c.setFont(self.font, isletter and 16 or 20)
        imgw, imgh = 2.83 * units.inch, .7 * units.inch

        c.drawString(25, h / 2 - 6, self.title)
        if self.logo_path:
            c.drawImage(self.logo_path, w - imgw - 25,
                        h / 2 - .5 * imgh, width=imgw, height=imgh,
                        preserveAspectRatio=True)
        c.setFillColorRGB(0, 0, 0)
        c.rect(0, h / 2 + .5 * imgh + 5, w, 1, fill=1)
        c.rect(0, h / 2 - .5 * imgh - 5, w, 1, fill=1)
        c.setFontSize(isletter and 12 or 16)
        c.drawString(25, h / 2 - .5 * imgh - 50, self.subtitle)
        if self.subtitle2:
            c.drawString(25, h / 2 - .5 * imgh - 70, self.subtitle2)
        c.restoreState() 
Example #4
Source File: report_delivery.py    From callisto-core with GNU Affero General Public License v3.0 6 votes vote down vote up
def generate(cls, pdf_input_data: dict):
        # setup
        self = cls()
        reports = pdf_input_data.get("reports", [])
        matches = pdf_input_data.get("matches", [])
        report_buffer = BytesIO()
        doc = SimpleDocTemplate(
            report_buffer,
            pagesize=letter,
            rightMargin=72,
            leftMargin=72,
            topMargin=72,
            bottomMargin=72,
        )

        # content fill
        self.pdf_elements.extend(self.cover_page())
        self.pdf_elements.extend(self.report_pages(reports))
        self.pdf_elements.extend(self.match_pages_empty_identifier(matches))

        # teardown
        doc.build(self.pdf_elements, canvasmaker=NumberedCanvas)
        result = report_buffer.getvalue()
        report_buffer.close()
        return result 
Example #5
Source File: PlotDecomposition_DBS78.py    From SigProfilerExtractor with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def gen_decomposition(denovo_name, basis_names, weights, output_path, project, reconstruction, statistics):

	c = canvas.Canvas(output_path+"/"+denovo_name+"_decomposition_"+project+".pdf", pagesize=letter)
	c.setPageSize(landscape(letter))
	c.setFont("Arial-Bold", 7.19)

	basis_plots = []
	for i in range(0,len(basis_names)):
		basis_plots.append([basis_names[i], weights[i]])


	# create for loop to iterate through list, then change second value in list of lists
	# Otherwise sorts strings and then 5.14% > 48.54%
	for j in range(0, len(basis_names)):
		basis_plots[j][1] = float(basis_plots[j][1].strip("%"))
	sorted_list = sorted(basis_plots, key=lambda tup: tup[1], reverse=True)

	gen_plot(denovo_name, sorted_list, output_path, project, c, reconstruction, statistics)

	c.save() 
Example #6
Source File: PlotDecomposition_SBS96.py    From SigProfilerExtractor with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def gen_decomposition(denovo_name, basis_names, weights, output_path, project, reconstruction, statistics):

	c = canvas.Canvas(output_path+"/"+denovo_name+"_decomposition_"+project+".pdf", pagesize=letter)
	c.setPageSize(landscape(letter))
	c.setFont("Arial-Bold", 7.19)

	basis_plots = []
	for i in range(0,len(basis_names)):
		basis_plots.append([basis_names[i], weights[i]])


	# create for loop to iterate through list, then change second value in list of lists
	# Otherwise sorts strings and then 5.14% > 48.54%
	for j in range(0, len(basis_names)):
		basis_plots[j][1] = float(basis_plots[j][1].strip("%"))
	sorted_list = sorted(basis_plots, key=lambda tup: tup[1], reverse=True)

	gen_plot(denovo_name, sorted_list, output_path, project, c, reconstruction, statistics)

	c.save() 
Example #7
Source File: PlotDecomposition_SBS1536.py    From SigProfilerExtractor with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def gen_decomposition(denovo_name, basis_names, weights, output_path, project, reconstruction, statistics):
	# Note: 0th index contains the title of the column
	c = canvas.Canvas(output_path+"/"+denovo_name+"_decomposition_"+project+".pdf", pagesize=letter)
	c.setPageSize(landscape(letter))
	c.setFont("Arial-Bold", 7.19)

	basis_plots = []
	for i in range(0,len(basis_names)):
		basis_plots.append([basis_names[i], weights[i]])

	# create for loop to iterate through list, then change second value in list of lists
	# Otherwise sorts strings and then 5.14% > 48.54%
	for j in range(0, len(basis_names)):
		basis_plots[j][1] = float(basis_plots[j][1].strip("%"))
	sorted_list = sorted(basis_plots, key=lambda tup: tup[1], reverse=True)

	gen_plot(denovo_name, sorted_list, output_path, project, c, reconstruction, statistics)

	c.save() 
Example #8
Source File: PlotDecomposition_DBS78.py    From SigProfilerExtractor with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def gen_decomposition(denovo_name, basis_names, weights, output_path, project, reconstruction, statistics):

	c = canvas.Canvas(output_path+"/"+denovo_name+"_decomposition_"+project+".pdf", pagesize=letter)
	c.setPageSize(landscape(letter))
	c.setFont("Arial-Bold", 7.19)

	basis_plots = []
	for i in range(0,len(basis_names)):
		basis_plots.append([basis_names[i], weights[i]])


	# create for loop to iterate through list, then change second value in list of lists
	# Otherwise sorts strings and then 5.14% > 48.54%
	for j in range(0, len(basis_names)):
		basis_plots[j][1] = float(basis_plots[j][1].strip("%"))
	sorted_list = sorted(basis_plots, key=lambda tup: tup[1], reverse=True)

	gen_plot(denovo_name, sorted_list, output_path, project, c, reconstruction, statistics)

	c.save() 
Example #9
Source File: PlotDecomposition_SBS96.py    From SigProfilerExtractor with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def gen_decomposition(denovo_name, basis_names, weights, output_path, project, reconstruction, statistics):

	c = canvas.Canvas(output_path+"/"+denovo_name+"_decomposition_"+project+".pdf", pagesize=letter)
	c.setPageSize(landscape(letter))
	c.setFont("Arial-Bold", 7.19)

	basis_plots = []
	for i in range(0,len(basis_names)):
		basis_plots.append([basis_names[i], weights[i]])


	# create for loop to iterate through list, then change second value in list of lists
	# Otherwise sorts strings and then 5.14% > 48.54%
	for j in range(0, len(basis_names)):
		basis_plots[j][1] = float(basis_plots[j][1].strip("%"))
	sorted_list = sorted(basis_plots, key=lambda tup: tup[1], reverse=True)

	gen_plot(denovo_name, sorted_list, output_path, project, c, reconstruction, statistics)

	c.save() 
Example #10
Source File: PlotDecomposition_ID83.py    From SigProfilerExtractor with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def gen_decomposition(denovo_name, basis_names, weights, output_path, project, reconstruction, statistics):
	# Note: 0th index contains the title of the column
	c = canvas.Canvas(output_path+"/"+denovo_name+"_decomposition_"+project+".pdf", pagesize=letter)
	c.setPageSize(landscape(letter))
	c.setFont("Arial-Bold", 7.19)

	basis_plots = []
	for i in range(0,len(basis_names)):
		basis_plots.append([basis_names[i], weights[i]])


	# create for loop to iterate through list, then change second value in list of lists
	# Otherwise sorts strings and then 5.14% > 48.54%
	for j in range(0, len(basis_names)):
		basis_plots[j][1] = float(basis_plots[j][1].strip("%"))
	sorted_list = sorted(basis_plots, key=lambda tup: tup[1], reverse=True)

	gen_plot(denovo_name, sorted_list, output_path, project, c, reconstruction, statistics)

	c.save() 
Example #11
Source File: pdf_form_display.py    From intake with MIT License 6 votes vote down vote up
def draw_letter(self):
        max_width = u('6.5in')
        max_height = self.height - (
            self.frame.top + self.frame.bottom)
        self.set_cursor(u('1in'), self.height - self.frame.top)
        dx, dy = self.draw_paragraph(
            self.nice_date, max_width, max_height, BODY_STYLE)
        self.move_cursor(0, -(dy + self.field_bottom_margin))
        dx, dy = self.draw_paragraph(
            "To Whom It May Concern,", max_width, max_height, BODY_STYLE)
        self.move_cursor(0, -(dy + self.field_bottom_margin))
        for field in self.keys_to_fields(self.letter_display_fields, 'letter'):
            dx, dy = self.draw_paragraph(
                field.get_display_value(), max_width, max_height, BODY_STYLE)
            self.move_cursor(0, -(dy + self.field_bottom_margin))
        dx, dy = self.draw_paragraph(
            "Sincerely,", max_width, max_height, BODY_STYLE)
        self.move_cursor(0, -(dy + self.field_bottom_margin))
        full_name = " ".join([
            self.form.first_name.get_display_value(),
            self.form.last_name.get_display_value()
        ])
        dx, dy = self.draw_paragraph(
            full_name, max_width, max_height, BODY_STYLE) 
Example #12
Source File: pdf_form_display.py    From intake with MIT License 6 votes vote down vote up
def __init__(self, display_form, letter_display=None, canvas=None):
        self.file = io.BytesIO()
        self.width, self.height = letter
        self.canvas = canvas
        if not canvas:
            self.canvas = Canvas(
                self.file,
                pagesize=letter)
            self.canvas.setAuthor('Clear My Record, Code for America')
        self.frame = Margin(
            u('1in'),
            u('.75in'),
            u('1in'),
            u('.75in'))
        self.form = display_form
        self.letter = letter_display
        self.cursor = Position(
            self.frame.left,
            self.height - self.frame.top
        )
        self.nice_date = \
            self.form.date_received.get_current_value().strftime("%B %-d, %Y") 
Example #13
Source File: templates.py    From HH---POS-Accounting-and-ERP-Software with MIT License 5 votes vote down vote up
def __init__(self, invoice_path, pdf_info=None, precision='0.01'):
        if not pdf_info:
            pdf_info = self.default_pdf_info

        SimpleDocTemplate.__init__(
            self,
            invoice_path,
            pagesize=letter,
            rightMargin=inch,
            leftMargin=inch,
            topMargin=inch,
            bottomMargin=inch,
            **pdf_info.__dict__
        )

        self.precision = precision

        self._defined_styles = getSampleStyleSheet()
        self._defined_styles.add(
            ParagraphStyle('RightHeading1', parent=self._defined_styles.get('Heading1'), alignment=TA_RIGHT)
        )
        self._defined_styles.add(
            ParagraphStyle('TableParagraph', parent=self._defined_styles.get('Normal'), alignment=TA_CENTER)
        )

        self.invoice_info = None
        self.service_provider_info = None
        self.client_info = None
        self.is_paid = False
        self._items = []
        self._item_discount_rate = None
        self._transactions = []
        self._story = []
        self._bottom_tip = None
        self._bottom_tip_align = None
        self._amount_recieved = None 
Example #14
Source File: builder.py    From tia with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def build_doc(cls, path, pagesize=None, showBoundary=1, allowSplitting=1, **dargs):
        if pagesize is None:
            pagesize = landscape(letter)
        return BaseDocTemplate(path, pagesize=pagesize, showBoundary=showBoundary, allowSplitting=allowSplitting,
                               **dargs) 
Example #15
Source File: accountStatmentMaker.py    From HH---POS-Accounting-and-ERP-Software with MIT License 5 votes vote down vote up
def makeAccountStatement (holder, rows, date=datetime.now()):
	from reportlab.pdfgen import canvas
	date = str(date)

	canvas = canvas.Canvas("accounts/" + holder.replace('/', "") + ".pdf", pagesize=letter)
	canvas.setLineWidth(.3)
	canvas.setFont('Helvetica', 12)
	
	canvas.drawString(30,750, 'Account Statement of ' + holder)
	canvas.drawString(30,735, 'At ACME INDUSTRIES')
	canvas.drawString(420,750, date)

	# heading
	makeHeader(canvas)

	diff = 0
	for r in rows:
		verticalPos = 650-diff
		
		if verticalPos == 50:
			canvas.showPage()
			makeHeader(canvas)
			verticalPos = 650
			diff = 0
			
		
		canvas.drawString(20,verticalPos,r[0])
		canvas.drawString(90,verticalPos,r[1][:-1])
		canvas.drawString(150,verticalPos,r[2])
		canvas.drawString(280,verticalPos,r[3])
		canvas.drawString(360,verticalPos,r[4])
		canvas.drawString(420,verticalPos,r[5])
		canvas.drawString(480,verticalPos,r[6])
		
		diff = diff + 50
	
	canvas.save() 
Example #16
Source File: qr_code_utilities.py    From Food-Pantry-Inventory with MIT License 5 votes vote down vote up
def initialize_pdf_file(self, buffer):
        """
        Prepare to scribble on a new pdf file.

        :param buffer:  May be a string with a filename or a BytesIO or other
            File-like object

        """
        self.pdf: Canvas(buffer, pagesize=letter) 
Example #17
Source File: qr_code_utilities.py    From Food-Pantry-Inventory with MIT License 5 votes vote down vote up
def __init__(self, url_prefix):

        self.url_prefix = url_prefix

        self.pdf: Canvas

        width, height = letter
        self.width: int = width
        self.height: int = height
        self.next_pos = 0 
Example #18
Source File: QRCodePrinter.py    From Food-Pantry-Inventory with MIT License 5 votes vote down vote up
def initialize_pdf_file(self):
        """
        Setup the pdf to receive labels.

        :return:
        """
        self.pdf = Canvas(str(self.full_path), pagesize=letter)
        self.width, self.height = letter

        return 
Example #19
Source File: recipe-535155.py    From code with MIT License 5 votes vote down vote up
def generate_card(IMG_FILE,IMG_URL,TEXT_FRONT,TEXT_INSIDE):
    """Main function to generate PDF and print to stdout. Designed to be
    run as a CGI application."""
    if not (IMG_FILE or IMG_URL):
        print 'You must upload an image file or provide a URL to one'
        return

    tmp = StringIO()

    #Canvas Setup
    c = canvas.Canvas(tmp, pagesize=letter, pageCompression=0)
    #If output size is important set pageCompression=1, but remember that, compressed documents
    #will be smaller, but slower to generate. Note that images are always compressed, and this option will only
    #save space if you have a very large amount of text and vector graphics on each page.
    #Do I need 'MacRomanEncoding' for Macs?
    #Note: 0,0 coordinate in canvas is bottom left.
    c.setAuthor('Utility Mill - utilitymill.com/utility/greeting_card_generator')
    c.setTitle('Beautiful, expensive greeting card created at utilitymill.com')

    #add_fold_lines(c) #early feedback says lines aren't necessary. Uncomment here to put them in
    put_in_front_picture(c,IMG_FILE,IMG_URL)
    write_text(c,TEXT_FRONT.replace('\r',''),TEXT_INSIDE.replace('\r',''))

    #The showPage method saves the current page of the canvas
    c.showPage()
    #The save method stores the file and closes the canvas.
    c.save()

    tmp.seek(0)
    print 'Content-Type: application/pdf'
    print tmp.read() 
Example #20
Source File: report_delivery.py    From callisto-core with GNU Affero General Public License v3.0 5 votes vote down vote up
def generate_pdf_report(self, report_id, recipient):
        # setup
        report_buffer = BytesIO()
        doc = SimpleDocTemplate(
            report_buffer,
            pagesize=letter,
            rightMargin=72,
            leftMargin=72,
            topMargin=72,
            bottomMargin=72,
        )

        # content fill
        self.pdf_elements.extend(
            api.NotificationApi.get_cover_page(report_id=report_id, recipient=recipient)
        )
        self.pdf_elements.extend(self.report_page(self.report))
        self.pdf_elements.append(
            Paragraph("Record Questions", self.section_title_style)
        )
        self.render_questions(self.report_data)

        # teardown
        doc.build(
            self.pdf_elements,
            onFirstPage=self.get_header_footer(recipient),
            onLaterPages=self.get_header_footer(recipient),
            canvasmaker=NumberedCanvas,
        )
        result = report_buffer.getvalue()
        report_buffer.close()
        return result 
Example #21
Source File: report_delivery.py    From callisto-core with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_header_footer(self, recipient):
        def func(canvas, doc):
            width, height = letter
            margin = 0.66 * 72
            canvas.saveState()
            canvas.setFillColor("gray")
            canvas.drawString(margin, height - margin, "CONFIDENTIAL")
            canvas.drawRightString(width - margin, height - margin, str(timezone.now()))
            canvas.restoreState()

        return func 
Example #22
Source File: report_delivery.py    From callisto-core with GNU Affero General Public License v3.0 5 votes vote down vote up
def draw_page_number(self, page_count):
        width, height = letter
        margin = 0.66 * 72
        self.setFillColor("gray")
        self.drawRightString(
            width - margin, margin, "Page %d of %d" % (self._pageNumber, page_count)
        ) 
Example #23
Source File: templates.py    From PyInvoice with MIT License 5 votes vote down vote up
def __init__(self, invoice_path, pdf_info=None, precision='0.01'):
        if not pdf_info:
            pdf_info = self.default_pdf_info

        SimpleDocTemplate.__init__(
            self,
            invoice_path,
            pagesize=letter,
            rightMargin=inch,
            leftMargin=inch,
            topMargin=inch,
            bottomMargin=inch,
            **pdf_info.__dict__
        )

        self.precision = precision

        self._defined_styles = getSampleStyleSheet()
        self._defined_styles.add(
            ParagraphStyle('RightHeading1', parent=self._defined_styles.get('Heading1'), alignment=TA_RIGHT)
        )
        self._defined_styles.add(
            ParagraphStyle('TableParagraph', parent=self._defined_styles.get('Normal'), alignment=TA_CENTER)
        )

        self.invoice_info = None
        self.service_provider_info = None
        self.client_info = None
        self.is_paid = False
        self._items = []
        self._item_tax_rate = None
        self._transactions = []
        self._story = []
        self._bottom_tip = None
        self._bottom_tip_align = None 
Example #24
Source File: pdf_form_display.py    From intake with MIT License 5 votes vote down vote up
def render(self, save=True, title=None):
        self.draw_header()
        self.draw_main_fields()
        self.draw_case_status_fields()
        self.canvas.showPage()
        if self.letter:
            self.draw_letter()
            self.canvas.showPage()
        if title:
            self.canvas.setTitle(title)
        if save:
            self.canvas.save()
        return self.canvas, self.file 
Example #25
Source File: report_delivery.py    From callisto-core with GNU Affero General Public License v3.0 4 votes vote down vote up
def generate_match_report(self, report_id, recipient):
        """
        Generates PDF report about a discovered match.

        Args:
          report_id (str): id used to uniquely identify this report to receiving authority

        Returns:
          bytes: a PDF with the submitted perp information & contact information of the reporters for this match

        """
        # setup :: matches
        sorted_matches = sorted(
            self.matches, key=lambda m: m.added.strftime("%Y-%m-%d %H:%M"), reverse=True
        )
        match_report_and_report_content = [
            (match, MatchReportContent(**json.loads(match.get_match(self.identifier))))
            for match in sorted_matches
        ]
        # setup :: pdf
        buffer = BytesIO()
        doc = SimpleDocTemplate(
            buffer,
            pagesize=letter,
            rightMargin=72,
            leftMargin=72,
            topMargin=72,
            bottomMargin=72,
        )

        # content fill
        self.pdf_elements.extend(
            api.NotificationApi.get_cover_page(report_id=report_id, recipient=recipient)
        )
        self.pdf_elements.append(
            Paragraph(api.NotificationApi.report_title, self.report_title_style)
        )
        self.pdf_elements.append(Paragraph("Perpetrator(s)", self.section_title_style))
        self.pdf_elements.append(
            self.names_and_matching_identifiers(match_report_and_report_content)
        )
        self.pdf_elements.extend(self.match_pages(match_report_and_report_content))

        # teardown
        doc.build(
            self.pdf_elements,
            onFirstPage=self.get_header_footer(recipient),
            onLaterPages=self.get_header_footer(recipient),
            canvasmaker=NumberedCanvas,
        )
        result = buffer.getvalue()
        buffer.close()
        return result 
Example #26
Source File: utils.py    From asm3 with GNU General Public License v3.0 4 votes vote down vote up
def html_to_pdf_pisa(dbo, htmldata):
    """
    Converts HTML content to PDF and returns the PDF file data as bytes.
    NOTE: wkhtmltopdf is far superior, but this is a pure Python solution and it does work.
    """
    # Allow orientation and papersize to be set
    # with directives in the document source - eg: <!-- pdf orientation landscape, pdf papersize letter -->
    orientation = "portrait"
    # Sort out page size arguments
    papersize = "A4"
    if htmldata.find("pdf orientation landscape") != -1: orientation = "landscape"
    if htmldata.find("pdf orientation portrait") != -1: orientation = "portrait"
    if htmldata.find("pdf papersize a5") != -1: papersize = "A5"
    if htmldata.find("pdf papersize a4") != -1: papersize = "A4"
    if htmldata.find("pdf papersize a3") != -1: papersize = "A3"
    if htmldata.find("pdf papersize letter") != -1: papersize = "letter"
    # Zoom - eg: <!-- pdf zoom 0.5 end -->
    # Not supported in any meaningful way by pisa (not smart scaling)
    # zm = regex_one("pdf zoom (.+?) end", htmldata)
    # Margins, top/bottom/left/right eg: <!-- pdf margins 2cm 2cm 2cm 2cm end -->
    margins = "2cm"
    mg = regex_one("pdf margins (.+?) end", htmldata)
    if mg != "":
        margins = mg
    header = "<!DOCTYPE html>\n<html>\n<head>"
    header += '<style>'
    header += '@page {size: %s %s; margin: %s}' % ( papersize, orientation, margins )
    header += '</style>' 
    header += "</head><body>"
    footer = "</body></html>"
    htmldata = htmldata.replace("font-size: xx-small", "font-size: 6pt")
    htmldata = htmldata.replace("font-size: x-small", "font-size: 8pt")
    htmldata = htmldata.replace("font-size: small", "font-size: 10pt")
    htmldata = htmldata.replace("font-size: medium", "font-size: 14pt")
    htmldata = htmldata.replace("font-size: large", "font-size: 18pt")
    htmldata = htmldata.replace("font-size: x-large", "font-size: 24pt")
    htmldata = htmldata.replace("font-size: xx-large", "font-size: 36pt")
    # Remove any img tags with signature:placeholder/user as the src
    htmldata = re.sub(r'<img.*?signature\:.*?\/>', '', htmldata)
    # Fix up any google QR codes where a protocol-less URI has been used
    htmldata = htmldata.replace("\"//chart.googleapis.com", "\"http://chart.googleapis.com")
    # Switch relative document uris to absolute service based calls
    htmldata = fix_relative_document_uris(dbo, htmldata)
    # Do the conversion
    from xhtml2pdf import pisa
    out = bytesio()
    pdf = pisa.pisaDocument(stringio(header + htmldata + footer), dest=out)
    if pdf.err:
        raise IOError(pdf.err)
    return out.getvalue()