Example #1
0
def pdf_fill(orig_pdf,vals):
    print "pdf_fill",orig_pdf,vals

    fields=[]
    for k,v in vals.items():
        fields.append((k,v,))

    orig_pdf_abs=os.path.join(os.getcwd(),orig_pdf)
    # tmp=os.tempnam()

    #jy_serv.pdf_fill(orig_pdf_abs,tmp,vals)

    # pdf=file(tmp).read()

    data_fdf= '%s.fdf' % uuid.uuid4()
    src_pdf = orig_pdf_abs
    output_pdf = '%s.pdf' % uuid.uuid4()

    fdf = forge_fdf("",fields,[],[],[])
    fdf_file = open(data_fdf,"wb")
    fdf_file.write(fdf)
    fdf_file.close()

    # system command to fill
    cmd = "/usr/bin/pdftk %s fill_form %s output %s flatten" % (src_pdf,data_fdf,output_pdf,)
    os.system(cmd)

    # read to iostream
    pdf=file(output_pdf).read()
    # remove temporay file
    os.unlink(output_pdf)
    os.unlink(data_fdf)

    return pdf
Example #2
0
def get_filled_pdf_bytes(original_template, fields):
    from fdfgen import forge_fdf

    tmppath = tempfile.mkdtemp()
    template_file = os.path.join(tmppath, 'template.pdf')

    shutil.copy(original_template, template_file)

    data_file = os.path.join(tmppath, 'data.fdf')

    with open(data_file, "wb") as fdf_file:
        fdf_file.write(forge_fdf('', fields, [], [], []))

    output_file = os.path.join(tmppath, 'output.pdf')
    arguments = [
        'pdftk',
        template_file,
        "fill_form",
        data_file,
        "output",
        output_file,
        'flatten'
    ]
    try:
        output_bytes = shell_call(arguments, tmppath, output_file)
        return output_bytes
    except Exception as err:
        logging.error("Error during PDF FDF: %s", err)
    finally:
        shutil.rmtree(tmppath)
    return None
Example #3
0
def create_fdf(data):
	fields = []
	for k in data.keys():
		if k in NEW_KEYS:
			fields += [(k,data[k])]
		elif k == "Repairs":
			for i, repair in enumerate(data["Repairs"]):
				op_key = "OP " + str(i+1)
				roi_key = "ROI " + str(i+1)
				svc_key = "SVC " + str(i+1)
				fields += [(op_key, repair["op"])]
				fields += [(roi_key, repair["instruction"])]
				fields += [(svc_key, repair["svc"])]
		elif k == "Invoice":
			inv = str(data[k])
			for i in range(5,-1, -1):
				invoice_key = "D " + str(i)
				if inv:
					fields += [(invoice_key, inv[-1])]
					inv = inv[:-1]
				else:
					fields += [(invoice_key, "0")]
	fdf = forge_fdf("",fields,[],[],[])
	fdf_file = open("temp_data_new.fdf","wb")
	fdf_file.write(fdf)
	fdf_file.close()
Example #4
0
    def print_bill(self):
        fields = [
            ('shipping_name', self.order.shipping_firstname +
             ' ' + self.order.shipping_lastname),
            ('shipping_address1', self.order.shipping_address1),
            ('shipping_address2', self.order.shipping_address2),
            ('shipping_town', self.order.shipping_postcode +
             ' ' + self.order.shipping_city),
            ('order_date', self.order.order_date),
            ('payment_method', self.order.payment_method),
            ('total', self.order.total),
            ('tax', self.order.tax),
            ('box', self.order.box),
        ]

        fdf = forge_fdf("", fields, [], [], [])
        fdf_name = self.output_dir + '/' + self.order.order_id + '_' + self.order.shipping_lastname + '.fdf'
        with open(fdf_name, 'w') as fdf_file:
            fdf_file.write(fdf)

        pdf_name = self.output_dir + '/' + self.order.order_id + '_' + self.order.shipping_lastname + '.pdf'
        # pdftk vorlage.pdf fill_form data.fdf output ausgabe.pdf flatten
        subprocess.call(['pdftk',
                        self.template,
                        'fill_form',
                        fdf_name,
                        'output',
                        pdf_name,
                        'flatten'])
Example #5
0
    def print_bill(self):
        fields = [
            ('shipping_name', self.order.shipping_firstname + ' ' +
             self.order.shipping_lastname),
            ('shipping_address1', self.order.shipping_address1),
            ('shipping_address2', self.order.shipping_address2),
            ('shipping_town',
             self.order.shipping_postcode + ' ' + self.order.shipping_city),
            ('order_date', self.order.order_date),
            ('payment_method', self.order.payment_method),
            ('total', self.order.total),
            ('tax', self.order.tax),
            ('box', self.order.box),
        ]

        fdf = forge_fdf("", fields, [], [], [])
        fdf_name = self.output_dir + '/' + self.order.order_id + '_' + self.order.shipping_lastname + '.fdf'
        with open(fdf_name, 'w') as fdf_file:
            fdf_file.write(fdf)

        pdf_name = self.output_dir + '/' + self.order.order_id + '_' + self.order.shipping_lastname + '.pdf'
        # pdftk vorlage.pdf fill_form data.fdf output ausgabe.pdf flatten
        subprocess.call([
            'pdftk', self.template, 'fill_form', fdf_name, 'output', pdf_name,
            'flatten'
        ])
Example #6
0
def nv_mobility_assessment_pa(rform):

    # Map fields
    all_fields_key = [
        ("7 Name last first", 'patientnamelf'), ("Address", "patientaddress"),
        ("9b Age", "patientage"), ("11 Phone", "patientphone"),
        ("16 Name", "physicianname"), ("17 NPI", "physiciannpi"),
        ("18 Address include city state and zip", "physicianaddress"),
        ("19 Phone", "physicianphone"), ("20 Fax", "physicianfax")
    ]

    # Fill Data
    all_fields = [(x[0], rform.get(x[1], "")) for x in all_fields_key]
    all_fields += [("9a Date of Birth", datefix(rform.get('patientdob')))]

    # Fill Requested Equipment
    headers = ["hcpcs{}", "description{}", "modifier{}", "qty{}"]
    zheaders = ["hcpcs", "name", "modifier", "qty"]
    rl = createMapFromZohoString(rform.get('relatedrecord', ""))
    firstpage_items = rl[:19]
    for index, record in enumerate(firstpage_items):
        fill_headers = map(lambda x: x.format(index + 1), headers)
        fill_kv = zip(fill_headers,
                      [record.get(head, "") for head in zheaders])
        all_fields += fill_kv

    # Convert
    fdf_data = fdfgen.forge_fdf("", all_fields, [], [], [])
    fdf_file = open("forms/NV_Mobility_assessment_and_PA_form_data.fdf", "w+")
    fdf_file.write(fdf_data)
    fdf_file.close()
    pdftk_cmd = "/app/vendor/pdftk/bin/pdftk forms/NV_Mobility_assessment_and_PA_form.pdf fill_form forms/NV_Mobility_assessment_and_PA_form_data.fdf output NV_Mobility_assessment_and_PA_form.pdf"
    os.chmod("/app/vendor/pdftk/bin/pdftk", 0o777)
    os.system(pdftk_cmd)
    zoho_upload("NV_Mobility_assessment_and_PA_form.pdf", rform.get("poid"))
Example #7
0
def form_fill(fields, row_count):
    fdf = forge_fdf("", fields, [], [], [])
    fdf_file = open(tmp_file, "wb")
    fdf_file.write(fdf)
    fdf_file.close()
    # fill in with borrower last name if there is something there or it uses Demo
    filename_prefix = fields[19][1] + "_" if fields[19][1] else "Demo "
    output_file = '{0}{1}{2}.pdf'.format(output_folder, filename_prefix,
                                         fields[1][1].replace(" ", "_"))
    if os.path.isfile(output_file):
        while True:
            new_file_name = '{0}{1}{2}_{3}.pdf'.format(
                output_folder, filename_prefix, fields[1][1].replace(" ", "_"),
                row_count)
            if os.path.isfile(f'{new_file_name}'):
                row_count += 1
            else:
                output_file = new_file_name
                break
    print(output_file)

    cmd = 'pdftk "{0}" fill_form "{1}" output "{2}" dont_ask'.format(
        pdffilename, tmp_file, output_file)
    os.system(cmd)
    os.remove(tmp_file)
Example #8
0
def idaho_mcd_pa(rform):

    # Map fields
    all_fields_key = [("last_name", 'patient_last_name'),
                      ("first_name", "patient_first_name"),
                      ("medicaid_id", "patientmedicaid"),
                      ("provider_name", "patientprimaryinsurance"),
                      ("npi", "physiciannpi"),
                      ("contact_person", "primarycontact"),
                      ("phone", "providerphone")]

    # Fill Data
    all_fields = [(x[0], rform.get(x[1], "")) for x in all_fields_key]
    all_fields += [("dob", datefix(rform.get('patientdob')))]

    # Fill Requested Equipment
    headers = ["hcpcs{}", "description{}", "qty{}", "price{}"]
    zheaders = ["hcpcs", "name", "qty", "price"]
    rl = createMapFromZohoString(rform.get('relatedrecord', ""))
    firstpage_items = rl[:9]
    for index, record in enumerate(firstpage_items):
        fill_headers = map(lambda x: x.format(index + 1), headers)
        fill_kv = zip(fill_headers,
                      [record.get(head, "") for head in zheaders])
        all_fields += fill_kv

    # Convert
    fdf_data = fdfgen.forge_fdf("", all_fields, [], [], [])
    fdf_file = open("forms/idaho_mcd_pa_data.fdf", "w+")
    fdf_file.write(fdf_data)
    fdf_file.close()
    pdftk_cmd = "/app/vendor/pdftk/bin/pdftk forms/idaho_mcd_pa.pdf fill_form forms/idaho_mcd_pa_data.fdf output Idaho_MCD_DME_Wheelchair_Repair_PA.pdf"
    os.chmod("/app/vendor/pdftk/bin/pdftk", 0o777)
    os.system(pdftk_cmd)
    zoho_upload("Idaho_MCD_DME_Wheelchair_Repair_PA.pdf", rform.get("poid"))
Example #9
0
def nv_dme_prior_auth(rform):

    # Map fields
    all_fields_key = [("patient_name", 'patientnamelf'),
                      ("MID", "patientmedicaid"), ("Address", "patientstreet"),
                      ("Phone", "patientphone"), ("City", "patientcity"),
                      ("State", "patientstate"), ("Zip Code", "patientzip"),
                      ("age", "patientage"), ("pat_phone", "patientphone"),
                      ("physician", "physicianname")]

    # Fill Data
    all_fields = [(x[0], rform.get(x[1], "")) for x in all_fields_key]
    all_fields += [("DOB", datefix(rform.get('patientdob')))]

    # Fill Requested Equipment
    headers = ["hcpcs{}", "description{}", "modifier{}", "qty{}"]
    zheaders = ["hcpcs", "name", "modifier", "qty"]
    rl = createMapFromZohoString(rform.get('relatedrecord', ""))
    firstpage_items = rl[:7]
    for index, record in enumerate(firstpage_items):
        fill_headers = map(lambda x: x.format(index + 1), headers)
        fill_kv = zip(fill_headers,
                      [record.get(head, "") for head in zheaders])
        all_fields += fill_kv

    # Convert
    fdf_data = fdfgen.forge_fdf("", all_fields, [], [], [])
    fdf_file = open("forms/NV_DME_Prior_auth_form_data.fdf", "w+")
    fdf_file.write(fdf_data)
    fdf_file.close()
    pdftk_cmd = "/app/vendor/pdftk/bin/pdftk forms/NV_DME_Prior_auth_form.pdf fill_form forms/NV_DME_Prior_auth_form_data.fdf output NV_DME_Prior_auth_form.pdf"
    os.chmod("/app/vendor/pdftk/bin/pdftk", 0o777)
    os.system(pdftk_cmd)
    zoho_upload("NV_DME_Prior_auth_form.pdf", rform.get("poid"))
Example #10
0
def fillPDFForm(formPdf,
                fields,
                outputPdf="filled.pdf",
                input_is_fullpath=False,
                editable=False):
    """
        fill given pdf file with form fields with given attributes and store result in pdf file
    """
    # build data file
    fdffilename = "{}{}infdata.fdf".format(config.get('paths.tempdir'),
                                           str(random.random())[2:])
    outputPdf = "{}{}filled.pdf".format(config.get('paths.tempdir'),
                                        str(random.random())[2:])
    try:
        with open(fdffilename, 'wb') as fdf_file:
            fdf_file.write(fdfgen.forge_fdf(fdf_data_strings=fields))

        # fill data in form pdf and generate pdf
        pdftkcmd = [
            "pdftk", formPdf, "fill_form", fdffilename, "output", outputPdf
        ]
        if not editable:
            pdftkcmd.append("flatten")
        utils.process.call(pdftkcmd)

        if os.path.exists(fdffilename):
            os.remove(fdffilename)
    except Exception:
        logg.exception(
            "exception in workflow step addformpage, error while filling pdf form, ignoring"
        )

    return outputPdf if os.path.exists(
        outputPdf) else ""  # check if file created
Example #11
0
    def fill_form(self, fields, src):
        fdf_stream = forge_fdf(fdf_data_strings=fields)

        cmd = [self.pdftk_bin, src, 'fill_form', '-', 'output', '-', 'flatten']
        cmd = ' '.join(cmd)

        return self.run_cmd(cmd, fdf_stream)
Example #12
0
    def fill_form(slef, fields, src, pdftk_bin=None):
        if pdftk_bin is None:
            from django.conf import settings
            assert hasattr(
                settings, 'PDFTK_BIN'
            ), "PDF generation requires pdftk (http://www.pdflabs.com/tools/pdftk-the-pdf-toolkit/). Edit your PDFTK_BIN settings accordingly."
            pdftk_bin = settings.PDFTK_BIN

        fdf_stream = forge_fdf(fdf_data_strings=fields)

        cmd = [
            pdftk_bin,
            src,
            'fill_form',
            '-',
            'output',
            '-',
            'flatten',
        ]
        cmd = ' '.join(cmd)

        try:
            process = subprocess.Popen(cmd,
                                       stdin=subprocess.PIPE,
                                       stdout=subprocess.PIPE,
                                       shell=True)
            return process.communicate(input=fdf_stream)
        except OSError:
            return None
Example #13
0
def fill_pdf(data_obj,input_file,output_file):
    """
    Create a filled form pdf file
    @param data_obj: list of dictionary with pdf params and values
    @param input_file: pdf form file name (with path and extension)
    @param output_file: output file name (with path and extension)
    @return: result dictionary: {'code' : <code_value>, 'message' : <msg_value>}
             (<code_value>: 0 -> execution succesful, <> 0 execution error), <msg_value> contains error description if <code_value> is not 0)
    """
    #returning objects
    result = {'code' : 0,  'message': ''}

    #temporrary fdf file name
    temp_name = os.path.splitext(os.path.basename(input_file))[0]
    temp_path = os.path.dirname(os.path.abspath(input_file))
    temp_fdf = "%s/%s" % (temp_path,temp_name)

    #get fileds and values
    fdf = forge_fdf("",data_obj,[],[],[])

    #make temporary file settings fileds with values
    try:
        fdf_file = open(temp_fdf,"w")
        fdf_file.write(fdf)
        fdf_file.close()
    except IOError, (errno, strerror):
        result['code'] = -1
        result['message'] = "Can't write temporary file! I/O error (%s): %s" % (errno, strerror)
Example #14
0
def main():
    NAMESLIST = input('Name list(.csv): ')
    PDFORI = input('Original pdf file (.pdf): ')

    names = []
    with open(NAMESLIST, "r") as f:
        reader = csv.reader(f, delimiter=',')
        for row in reader:
            for x in row:
                names.append(x)

    numfile = 0

    for i in names:
        fields = [('Name', i)]
        z = i.replace(" ", "")
        print('creating {0}.pdf...'.format(z))
        fdf = forge_fdf("", fields, [], [], [])
        fdf_file = open("tmp.fdf", "wb")
        fdf_file.write(fdf)
        fdf_file.close()
        cmd = 'pdftk {0} fill_form tmp.fdf output {1}.pdf flatten'.format(
            PDFORI, z)
        os.system(cmd)
        numfile += 1
        print('{0}.pdf created'.format(z))

    print('END OF PROCESS: {0} FILES CREATED'.format(numfile))
Example #15
0
    def exec_pdftk(self, data):
    	logging.debug('Data for fdf filling: ')
        logging.debug(data.items())

        fdf = forge_fdf("", data.items(), [], [], [], checkbox_checked_name="Yes")
        fdf_file = open("fdf.fdf", "wb")
        fdf_file.write(fdf)
        fdf_file.close()        
        args = [
            "pdftk",
            self.filename,
            "fill_form", "-",
            "output", "-",
            "dont_ask",
            "flatten"
        ]
        logging.debug('Pdftk args: ')
        logging.debug(args)

        p = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE)
        stdout, stderr = p.communicate(fdf)
        logging.debug('Result: ')
        logging.debug(stdout)
     
        if stderr.strip():
        	logging.debug('Errors: ')
            logging.debug(stderr)
            raise IOError(stderr)
Example #16
0
def generate_contract_de_fdf_pdf(user):
    """
    take user information and generate fdf
    """
    if DEBUG:  # pragma: no cover
        print "===== this is generate_fdf_pdf"
    from fdfgen import forge_fdf
    fields = [
        ('surname', user.surname),
        ('lastname', user.lastname),
        ('street', user.street),
        ('number', user.number),
        ('postcode', user.postcode),
        ('city', user.city),
        ('email', user.email),
        ('user_id', user.id),
        ('username', user.username),
        ('date_registered', user.date_registered),
        ('date_generated', datetime.now()),
        ]
    #generate fdf string
    fdf = forge_fdf("", fields, [], [], [])
    # write to file
    my_fdf_filename = "fdf" + str(user.id) + ".fdf"

    fdf_file = open(my_fdf_filename, "w")
    fdf_file.write(fdf)
    fdf_file.close()
    if DEBUG:  # pragma: no cover
        print "fdf file written."

    res = os.popen(
        'pdftk pdftk/berechtigungsvertrag-2.2.pdf fill_form %s output'
        ' formoutput.pdf flatten' % my_fdf_filename).read()

    if DEBUG:  # pragma: no cover
        print res
        print "done: put data into form and finalized it"

    # delete the fdf file
    res = os.popen('rm %s' % my_fdf_filename)
    if DEBUG:  # pragma: no cover
        print res
        print "combining with bank account form"
    # combine
    res = os.popen(
        'pdftk formoutput.pdf pdftk/bankaccount.pdf output output.pdf').read()
    if DEBUG:  # pragma: no cover
        print res
        print "combined personal form and bank form"

    # delete the fdf file
    os.popen('rm formoutput.pdf').read()

    # return a pdf file
    from pyramid.response import Response
    response = Response(content_type='application/pdf')
    response.app_iter = open("output.pdf", "r")
    return response
Example #17
0
    def _createFDF(self, fields):
        fdf = forge_fdf("",fields,[],[],[])
        fdf_file = tempfile.NamedTemporaryFile()
        fdf_file.write(fdf)
        fdf_file.seek(0) # need to rewind the file handle in order to read form it
        # remember to fdf_file.close() at the end of the program

        return fdf_file
Example #18
0
def build_fdf(fields, filename):
    if fields != [] and filename != 'none':
        fdf = forge_fdf("", fields, [], [], [])
        fdf_file = open(filename, "wb")
        fdf_file.write(fdf)
        fdf_file.close()
    else:
        print("error in buildfdf - fields were empty and filename was none")
Example #19
0
def fill_pdf_template(row, pdf_template, output_file):
    tmp_file = "tmp.fdf"
    fdf = forge_fdf("", row, [], [], [])
    with open(tmp_file, "wb") as fdf_file:
        fdf_file.write(fdf)
    cmd = "pdftk '{0}' fill_form '{1}' output '{2}' dont_ask".format(pdf_template, tmp_file, output_file)
    os.system(cmd)
    os.remove(tmp_file)
Example #20
0
def generate_pdf(fields, template, output):
	fdf = forge_fdf('', fields.items(), [], [], [])
	temp = tempfile.NamedTemporaryFile()
	with open(temp.name, 'w') as fdf_file:
		fdf_file.write(fdf)
	getoutput('pdftk %s fill_form %s output %s.pdf flatten' % (template, fdf_file.name, output))
	fdf_file.close()
	temp.close()
Example #21
0
def main(input_fields_file):
    if input_fields_file != "-":
        with open(input_fields_file, "r") as input_fields_fd:
            fields = parse_fields(input_fields_fd)
    else:
        fields = parse_fields(sys.stdin)
    fdf = forge_fdf("", fields, [], [])
    sys.stdout.buffer.write(fdf)
Example #22
0
    def fill_form(self, fields, src, pdftk_bin=None):
        fdf_stream = forge_fdf(fdf_data_strings=fields)

        #cmd = [self.pdftk_bin, src, 'fill_form', '-', 'output', '-', 'flatten']
        cmd = [self.pdftk_bin, src, 'fill_form', '-', 'output', '-']
        cmd = ' '.join(cmd)

        return self.run_cmd(cmd, fdf_stream)
Example #23
0
def generate_invoice_file(invoice_id):
    invoice = Invoice.query.filter(Invoice.id==invoice_id).first()
    fields = [('name','John Smith'),('telephone','555-1234')]
    fdf = forge_fdf("",fields,[],[],[])
    fdf_file = open("data.fdf","wb")
    fdf_file.write(fdf)
    fdf_file.close()
    return redirect(url_for('index'))
Example #24
0
def fill_template(template, data_strings=[], data_names=[], hidden=[], readonly=[], images=[], pdf_url=''):
    fdf = fdfgen.forge_fdf(pdf_url, data_strings, data_names, hidden, readonly)
    fdf_file = tempfile.NamedTemporaryFile(mode="wb", suffix=".fdf", delete=False)
    fdf_file.write(fdf)
    fdf_file.close()
    pdf_file = tempfile.NamedTemporaryFile(mode="wb", suffix=".pdf", delete=False)
    subprocess_arguments = [PDFTK_PATH, template, 'fill_form', fdf_file.name,'output', pdf_file.name, 'flatten']
    result = call(subprocess_arguments)
    if result != 0:
        logmessage("Failed to fill PDF form " + str(template))
        raise DAError("Call to pdftk failed for template " + str(template) + " where arguments were " + " ".join(subprocess_arguments))
    if len(images):
        fields = dict()
        for field, default, pageno, rect, field_type in read_fields(template):
            if str(field_type) == '/Sig':
                fields[field] = {'pageno': pageno, 'rect': rect}
        for field, file_info in images:
            if field not in fields:
                logmessage("field name " + str(field) + " not found in PDF file")
                continue
            logmessage("Need to put image on page " + str(fields[field]['pageno']))
            temp_png = tempfile.NamedTemporaryFile(mode="wb", suffix=".png")
            args = ["convert", file_info['fullpath'], "-trim", "+repage", temp_png.name]
            result = call(args)
            if result == 1:
                logmessage("failed to trim file: " + " ".join(args))
                continue
            im = Image.open(temp_png.name)
            width, height = im.size
            xone, yone, xtwo, ytwo = fields[field]['rect']
            dppx = width/(xtwo-xone)
            dppy = height/(ytwo-yone)
            if (dppx > dppy):
                dpp = dppx
            else:
                dpp = dppy
            extent_x, extent_y = xone*dpp+width, yone*dpp+height
            overlay_pdf_file = tempfile.NamedTemporaryFile(mode="wb", suffix=".pdf")
            args = ["convert", temp_png.name, "-background", "none", "-density", str(int(dpp*72)), "-gravity", "NorthEast", "-extent", str(int(extent_x)) + 'x' + str(int(extent_y)), overlay_pdf_file.name]
            result = call(args)
            if result == 1:
                logmessage("failed to make overlay: " + " ".join(args))
                continue
            new_pdf_file = tempfile.NamedTemporaryFile(mode="wb", suffix=".pdf")
            with open(pdf_file.name, "rb") as inFile, open(overlay_pdf_file.name, "rb") as overlay:
                original = pypdf.PdfFileReader(inFile)
                background = original.getPage(fields[field]['pageno']-1)
                foreground = pypdf.PdfFileReader(overlay).getPage(0)
                background.mergePage(foreground)
                writer = pypdf.PdfFileWriter()
                for i in range(original.getNumPages()):
                    page = original.getPage(i)
                    writer.addPage(page)
                with open(new_pdf_file.name, "wb") as outFile:
                    writer.write(outFile)
            shutil.copyfile(new_pdf_file.name, pdf_file.name)
    return pdf_file.name
Example #25
0
def fill_template(template, data_strings=[], data_names=[], hidden=[], readonly=[], images=[], pdf_url=''):
    fdf = fdfgen.forge_fdf(pdf_url, data_strings, data_names, hidden, readonly)
    fdf_file = tempfile.NamedTemporaryFile(mode="wb", suffix=".fdf", delete=False)
    fdf_file.write(fdf)
    fdf_file.close()
    pdf_file = tempfile.NamedTemporaryFile(mode="wb", suffix=".pdf", delete=False)
    subprocess_arguments = [PDFTK_PATH, template, 'fill_form', fdf_file.name,'output', pdf_file.name, 'flatten']
    result = call(subprocess_arguments)
    if result != 0:
        logmessage("Failed to fill PDF form " + str(template))
        raise DAError("Call to pdftk failed for template " + str(template) + " where arguments were " + " ".join(subprocess_arguments))
    if len(images):
        fields = dict()
        for field, default, pageno, rect, field_type in read_fields(template):
            if str(field_type) == '/Sig':
                fields[field] = {'pageno': pageno, 'rect': rect}
        for field, file_info in images:
            if field not in fields:
                logmessage("field name " + str(field) + " not found in PDF file")
                continue
            logmessage("Need to put image on page " + str(fields[field]['pageno']))
            temp_png = tempfile.NamedTemporaryFile(mode="wb", suffix=".png")
            args = ["convert", file_info['fullpath'], "-trim", "+repage", temp_png.name]
            result = call(args)
            if result == 1:
                logmessage("failed to trim file: " + " ".join(args))
                continue
            im = Image.open(temp_png.name)
            width, height = im.size
            xone, yone, xtwo, ytwo = fields[field]['rect']
            dppx = width/(xtwo-xone)
            dppy = height/(ytwo-yone)
            if (dppx > dppy):
                dpp = dppx
            else:
                dpp = dppy
            extent_x, extent_y = xone*dpp+width, yone*dpp+height
            overlay_pdf_file = tempfile.NamedTemporaryFile(mode="wb", suffix=".pdf")
            args = ["convert", temp_png.name, "-background", "none", "-density", str(int(dpp*72)), "-gravity", "NorthEast", "-extent", str(int(extent_x)) + 'x' + str(int(extent_y)), overlay_pdf_file.name]
            result = call(args)
            if result == 1:
                logmessage("failed to make overlay: " + " ".join(args))
                continue
            new_pdf_file = tempfile.NamedTemporaryFile(mode="wb", suffix=".pdf")
            with open(pdf_file.name, "rb") as inFile, open(overlay_pdf_file.name, "rb") as overlay:
                original = pypdf.PdfFileReader(inFile)
                background = original.getPage(fields[field]['pageno']-1)
                foreground = pypdf.PdfFileReader(overlay).getPage(0)
                background.mergePage(foreground)
                writer = pypdf.PdfFileWriter()
                for i in range(original.getNumPages()):
                    page = original.getPage(i)
                    writer.addPage(page)
                with open(new_pdf_file.name, "wb") as outFile:
                    writer.write(outFile)
            shutil.copyfile(new_pdf_file.name, pdf_file.name)
    return pdf_file.name
Example #26
0
def form_fill(fields):
  fdf = forge_fdf("",fields,[],[],[])
  fdf_file = open(tmp_file,"w")
  fdf_file.write(fdf)
  fdf_file.close()
  output_file = '{0}{1} {2}.pdf'.format(output_folder, filename_prefix, fields[1][1])
  cmd = 'pdftk "{0}" fill_form "{1}" output "{2}" dont_ask'.format(pdf_file, tmp_file, output_file)
  os.system(cmd)
  os.remove(tmp_file)
Example #27
0
def write_notes(system, Vnominal=240.0):
    stationClass = 1
    name, usaf = geo.closestUSAF( geo.zipToCoordinates(system.zipcode), stationClass)
    mintemp = epw.minimum(usaf)
    twopercentTemp = epw.twopercent(usaf)
    fields = []
    for i in set(system.shape):
        print "PV Module Ratings @ STC"
        print "Module Make:", i.array.make
        fields.append(('Text1ModuleMake',i.array.make))
        print "Module Model:", i.array.model
        fields.append(('Text1ModuleModel',i.array.model))
        print "Max Power-Point Current (Imp):",i.array.Impp
        fields.append(('MAX POWERPOINT CURRENT IMP',i.array.Impp))
        print "Max Power-Point Voltage (Vmp):",i.array.Vmpp
        fields.append(('MAX POWERPOINT VOLTAGE VMP',i.array.Vmpp))
        print "Open-Circuit Voltage (Voc):",i.array.Voc
        fields.append(('OPENCIRCUIT VOLTAGE VOC',i.array.Voc))
        print "Short-Circuit Current (Isc):",i.array.Isc
        fields.append(('SHORTCIRCUIT CURRENT ISC',i.array.Isc))
        fields.append(('MAX SERIES FUSE OCPD','15'))
        print "Maximum Power (Pmax):",i.array.Pmax
        fields.append(('MAXIMUM POWER PMAX',i.array.Pmax))
        print "Module Rated Max Voltage:",i.array.Vrated
        fields.append(('MAX VOLTAGE TYP 600VDC',i.array.Vrated))
        fields.append(('VOC TEMP COEFF mVoC or oC',round(i.array.TkVoc,2)))
        fields.append(('VOC TEMP COEFF mVoC','On'))
        print "Inverter Make:",i.make
        fields.append(('INVERTER MAKE',i.make))
        print "Inverter Model:",i.model
        fields.append(('INVERTER MODEL',i.model))
        print "Max Power", i.Paco
        fields.append(('MAX POWER  40oC',i.model))
        fields.append(('NOMINAL AC VOLTAGE',240))
        print "Max AC Current: %s" % round(i.Paco/Vnominal,2)
        fields.append(('MAX AC CURRENT', round(i.Paco/Vnominal,2)))
        fields.append(('MAX DC VOLT RATING',i.model))
        print "Max AC OCPD Rating: %s" % ee.ocpSize(i.Paco/Vnominal*1.25)
        print "Max System Voltage:",round(i.array.Vmax(mintemp),1)
    print "AC Output Current: %s" % \
            round(sum([i.Paco for i in system.shape])/Vnominal,2)
    fields.append(('AC OUTPUT CURRENT', \
            round(sum([i.Paco for i in system.shape])/Vnominal,2)))
    print "Nominal AC Voltage: %s" % Vnominal
    fields.append(('NOMINAL AC VOLTAGE_2',i.ac_voltage))

    print "Minimum Temperature: %s C" % mintemp
    print "2 Percent Max: %s C" % twopercentTemp
    from fdfgen import forge_fdf
    fdf = forge_fdf("",fields,[],[],[])
    fdf_file = open("data.fdf","w")
    fdf_file.write(fdf)
    fdf_file.close()
    import shlex
    from subprocess import call
    cmd = shlex.split("pdftk Example2-Micro-Inverter.pdf fill_form data.fdf output output.pdf flatten")
    rc = call(cmd)
Example #28
0
 def create_form(self, datas):
     fdf = forge_fdf("", datas, [], [], [])
     fdf_file = open("data1.fdf", "wb")
     fdf_file.write(fdf)
     fdf_file.close()
     subprocess.call([
         "pdftk", "AFTP.pdf", "fill_form", "data1.fdf", "output",
         "outputAFTP.pdf", "flatten"
     ])
Example #29
0
def create_fdf(data_fields_dict):
	fields = []
	del data_fields_dict['RESET']
	for k in data_fields_dict.keys():
		fields += [(k,data_fields_dict[k]["possible_values"][0])]
	fdf = forge_fdf("",fields,[],[],[])
	fdf_file = open("data_new.fdf","wb")
	fdf_file.write(fdf)
	fdf_file.close()
Example #30
0
def generate_fdf(fields, data, fdfname):
    field_value_tuples = []
    for field in fields:
        field_value = (field, data[field])
        field_value_tuples.append(field_value)
    fdf = forge_fdf("", field_value_tuples, [], [], [])
    fdf_file = open(fdfname, "wb")
    fdf_file.write(fdf)
    fdf_file.close()
Example #31
0
def form_fill(fields, pdf_form, file_prefix, output_dir):
    tmp_file = "tmp.fdf"
    fdf = forge_fdf("",fields,[],[],[])
    fdf_file = open(tmp_file,"w")
    fdf_file.write(fdf)
    fdf_file.close()
    output_file = '{0}{1}{2}.pdf'.format(output_dir, file_prefix, fields[0][1])
    cmd = 'pdftk "{0}" fill_form "{1}" output "{2}" flatten'.format(pdf_form, tmp_file, output_file)
    os.system(cmd)
    os.remove(tmp_file)
Example #32
0
def writeFDFoverflow(all_fields):
    print "ALL FIELDS:\n"
    print all_fields
    fdf_data = fdfgen.forge_fdf("", all_fields, [], [], [])
    fdf_file = open("overflowfile_fdf.fdf", "w+")
    fdf_file.write(fdf_data)
    fdf_file.close()
    pdftk_cmd = "/app/vendor/pdftk/bin/pdftk utahPA_overflow.pdf fill_form overflowfile_fdf.fdf output Medicaid_overflow.pdf"
    os.chmod("/app/vendor/pdftk/bin/pdftk", 0o777)
    os.system(pdftk_cmd)
Example #33
0
 def create_form(self):
     self.fill_fields()
     fdf = forge_fdf("", self.datas, [], [], [])
     fdf_file = open("data.fdf", "wb")
     fdf_file.write(fdf)
     fdf_file.close()
     subprocess.call([
         "pdftk", "leaveForm.pdf", "fill_form", "data.fdf", "output",
         "output.pdf", "flatten"
     ])
Example #34
0
def create_form(field):

    fdf = forge_fdf("", field, [], [], [])
    fdf_file = open("data1.fdf", "wb")
    fdf_file.write(fdf)
    fdf_file.close()
    # fill_form("leaveForm.pdf", self.datas, "output.pdf")
    subprocess.call([
        "pdftk", "AFTP.pdf", "fill_form", "data1.fdf", "output",
        "outputAFTP.pdf", "flatten"
    ])
def form_fill(fields):

    fdf = forge_fdf("", fields, [], [], [])
    fdf_file = open(tmp_file, "wb")
    fdf_file.write(fdf)
    fdf_file.close()
    output_file = "{0}{1}.pdf".format(output_folder, "Adeldian")
    cmd = 'pdftk "{0}" fill_form "{1}" output "{2}" dont_ask'.format(pdf_file, tmp_file, output_file)
    # print(cmd)
    os.system(cmd)
    os.remove(tmp_file)
Example #36
0
def autocomplete_pdf(data, filepath):
    pair_list = to_pair_list(data)
    fdf_data = fdfgen.forge_fdf("", pair_list, [], [], [])
    fdf_file = open(FDF_FILENAME, "w")
    fdf_file.write(fdf_data)
    fdf_file.close()
    destination = '/'.join(str(filepath).split('/')[:-1]) + '/completed.pdf'
    pdftk_cmd = "pdftk %s fill_form %s output %s flatten" % (
        filepath, FDF_FILENAME, destination)
    os.system(pdftk_cmd)
    os.remove(FDF_FILENAME)
Example #37
0
def form_fill(fields):
    fdf = forge_fdf("", fields, [], [], [])
    fdf_file = open(tmp_file, "w")
    fdf_file.write(fdf)
    fdf_file.close()
    output_file = '{0}{1} {2}.pdf'.format(output_folder, filename_prefix,
                                          fields[1][1])
    cmd = 'pdftk "{0}" fill_form "{1}" output "{2}" dont_ask'.format(
        pdf_file, tmp_file, output_file)
    os.system(cmd)
    os.remove(tmp_file)
def gen_fdf(outfile='data.fdf'):
    '''Generate random numbers to form fill 10-liner cards, save FDF file.'''
    fields = []
    increment = 0
    for card in range(6):
        increment += 1
        cardname = 'Card '+str(increment)
        fields += gen_card(cardname)
    fdf = forge_fdf("",fields,[],[],[])
    fdf_file = open(outfile,"w")
    fdf_file.write(fdf)
    fdf_file.close()
Example #39
0
def process_submission(post_data):
    print 'beginning'
    samples_sheet = json.loads(post_data['samples_sheet'])
    print 'samples_sheet: {}'.format(str(samples_sheet))

    faber_form = FacilityForm(post_data)  # TODO initial=
    if not faber_form.is_valid():
        return False

    # Get cleaned form data, create FDF file to fill out Faber core PDF
    faber_form_data = faber_form.cleaned_data
    faber_form_data['date'] = faber_form_data['date'].strftime('%m/%d/%Y')

    # fdf_fields = [
    #     (pdf_key, faber_form_data.get(web_key, None))
    #     for web_key, pdf_key
    #     in FacilityForm.web_to_pdf_field_map().iteritems()
    # ]
    fdf_fields = [('Sample Labels', 'sample labels test'), ('DNA', 'On'),
                  ('Other Run Type', 'Running it!'), ('RNA', 'On'),
                  ('SE 100 bp', ''), ('Index Manufacturer', 'Star Warts'),
                  ('2 lane flow cell Rapid Run', 'Off'), ('SE 50 bp', ''),
                  ('undefined_2', 'On'), ('None', 'On'), ('ChIP', 'Off'),
                  ('8 lane flow cell High Output', ''), ('Other_2', ''),
                  ('Billing Administrator', 'Heather'),
                  ('Sample Species', 'Human Pig Hybrid'),
                  ('Date mmddyyyy', '02/03/2017'), ('Dual 88', 'On'),
                  ('Experiment Contact Email  Phone', '911'),
                  ('Billing Administrator Email  Phone', '*****@*****.**'),
                  ('8 bases', ''), ('Number of Lanes Requested', '9000'),
                  ('EXOME', ''), ('undefined', 'On'), ('6 bases', ''),
                  ('PO #', '82'), ('Other', 'On'),
                  ('Comments', 'This is the comment box'), ('PE 50 bp', 'On'),
                  ('Experiment Contact', 'Dominic'), ('PE 100 bp', 'Off'),
                  ('Number of Tubes Submitted', '71'),
                  ('Principal Investigator Email  Phone',
                   '*****@*****.**'),
                  ('Department', 'Biological Sciences'), ('Other_3', 'On'),
                  ('Principal Investigator', 'Kevin Dubbs'),
                  ('Number of Samples per Tube', '34')]

    with open('/tmp/data.fdf', 'wb') as fdf_file:
        fdf_file.write(forge_fdf(fdf_data_strings=fdf_fields))

    # Combine the form data with the PDF, output to a new file
    subprocess.call([
        'pdftk', '/home/dfitzgerald/faber_submission.pdf', 'fill_form',
        '/tmp/data.fdf', 'output', '/home/dfitzgerald/faber_output.pdf'
    ])

    print 'returning true'

    return True
Example #40
0
def fill_pdf_form(input_pdf, entries, output_pdf, flatten=False):
    d = tempfile.mkdtemp()
    try:
        fdf_filename = pjoin(d, 'entries.fdf')
        with open(fdf_filename, 'w') as f:
            f.write(forge_fdf("", entries, [], [], []))
        args = ['pdftk', input_pdf, 'fill_form', fdf_filename, 'output', output_pdf]
        if flatten:
            args += ['flatten']
        check_call(args)
    finally:
        shutil.rmtree(d)
Example #41
0
    def exec_pdftk(self, data):
        fdf = forge_fdf("", data.items(), [], [], [])
        args = [
            "pdftk", self.filename, "fill_form", "-", "output", "-",
            "dont_ask", "flatten"
        ]

        p = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE)
        stdout, stderr = p.communicate(fdf)
        if stderr.strip():
            raise IOError(stderr)

        return BytesIO(stdout)
Example #42
0
def FillForm(list):
    #TODO finish this function
    fields_filled = []
    # for i in list:
    #     if not Field_to_ignore(i):

    # for testing only
    fields = [('Given Name Text Box', 'Bhavesh'),
              ('Family Name Text Box', 'Praveen')]
    fdf = forge_fdf("", fields)
    fdf_file = open('/home/ichigo/Desktop/test_outputs/data.fdf', 'wb')
    fdf_file.write(fdf)
    fdf_file.close()
 def run(self):
     fdf = forge_fdf("", self.fields, [], [], [])
     self.directory = self.directory.replace("/", "\\")
     out_filename = self.directory + "\\" + self.filename + ".pdf"
     fdf_filename = out_filename + ".fdf"
     fdf_file = open(fdf_filename, "wb")
     fdf_file.write(fdf)
     fdf_file.close()
     subprocess.call("pdftk " + self.template_file + " fill_form " +
                     fdf_filename + " output " + out_filename)
     print(fdf_filename)
     subprocess.call("del " + fdf_filename, shell=True)
     self.finished.emit(self.uuid)
Example #44
0
def gen_martins_fdf():
    """
    generates fdf file to patch the pdf form with

    """
    #generate fdf string
    fdf = forge_fdf("", gen_martins_fields(), [], [], [])
    # write to file
    fdf_file = open("testdata_martin.fdf", "w")
    fdf_file.write(fdf)
    fdf_file.close()

    print "fdf file written."
Example #45
0
def pdf_fill(email,input_pdf_file_name):

    # ********************************************************************************************************
    # * This figures out where the script is stored
    # ********************************************************************************************************
    script_path: Union[bytes, str] = os.path.dirname(os.path.realpath(sys.argv[0]))
    logging.debug('Script Directory:' + script_path)

    # ********************************************************************************************************
    # * Read in the pdf field names and values
    # ********************************************************************************************************
    input_fields_and_values_file = os.path.join(script_path, email) + '.txt'

    with open(input_fields_and_values_file) as f:
        all_fields = [tuple(i.strip().split(',')) for i in f]

    # ********************************************************************************************************
    # * Build the fully qualified file names
    # ********************************************************************************************************
    fdf_file_name = os.path.join(script_path, "file_fdf.fdf")
    base_output_f_name = os.path.split(input_pdf_file_name)[1]  # Extract the file name with extension
    base_output_f_name = os.path.splitext(base_output_f_name)   # Split the file name and extension
    output_f_name = base_output_f_name[0] + r'_output.pdf'      # Build the output file name with extension
#    output_file_name = os.path.join(script_path, output_f_name) # Build the fully qualified file name
    output_file_name = os.path.join(os.path.dirname(input_pdf_file_name), output_f_name) # Build the fully qualified file name

    # ********************************************************************************************************
    # * Create FDF file with the fields read from the file earlier
    # ********************************************************************************************************
    fdf_data = fdfgen.forge_fdf("", all_fields, [], [], [])
    fdf_file = open(fdf_file_name, "wb")
    fdf_file.write(fdf_data)
    fdf_file.close()

    # ********************************************************************************************************
    # * Run pdftk system command to populate the pdf file.
    # * The file "file_fdf.fdf" is pushed in to "input_pdf.pdf" thats generated as a new "output_pdf.pdf" file.
    # ********************************************************************************************************
    input_pdf_file_name1 = '"' + input_pdf_file_name + '"'
    output_file_name1 = '"' + output_file_name + '"'
    pdftk_cmd = "pdftk " + input_pdf_file_name1 + \
                " fill_form " + fdf_file_name + \
                " output " + output_file_name1 + " flatten"
    logging.debug('pdftk command:' + pdftk_cmd)
    os.system(pdftk_cmd)
    # ********************************************************************************************************
    # * Remove the fdf file
    # ********************************************************************************************************
    os.remove(fdf_file_name)
    return output_file_name
def generate_pdf(values, source_filename, fdf_filename, output_filename):
  # values: dictionary of fieldname, value
  fdf_fields = []

  for fieldname, value in values.iteritems():
    fdf_fields.append((fieldname, value))

  fdf = forge_fdf("", fdf_fields, [], [], [])

  fdf_file = open(fdf_filename, "w")
  fdf_file.write(fdf)
  fdf_file.close()

  subprocess.call(['pdftk', source_filename ,'fill_form', fdf_filename, 'output', output_filename])
Example #47
0
def generate_pdfs(persons, maßnahmenzeitraum, datum, kif_ev, maßname,
                  leer_blaetter):
    seite = 1
    data_file = "data_fdf.bin"
    output_file_name = "output"
    personen_pro_seite = 14

    #check if vorlage exits
    test_file = Path(vorlage)
    if not test_file.is_file():
        print("[X] File {} not found!".format(vorlage))
        exit(-1)

    anzahl_seiten = ceil(len(persons) / personen_pro_seite)
    pdfs = []

    for j in range(anzahl_seiten + leer_blaetter):
        felder = []
        i = 0
        for item in form_mapping:
            if personen_pro_seite * j + i < len(persons):
                felder.append((item[0], str(j * personen_pro_seite + i + 1)))
                felder.append(
                    (item[1], persons[j * personen_pro_seite + i]["Name"]))
                felder.append(
                    (item[2],
                     persons[j * personen_pro_seite + i]["Hochschule"]))
            i += 1

            if i == personen_pro_seite:
                output_file = output_file_name + str(seite) + ".pdf"

                headers = [("1", seite), ("2", maßnahmenzeitraum),
                           ("3", datum), ("4", kif_ev), ("5", maßname)]

                fields = felder + headers

                fdf = forge_fdf("", fields, [], [], [])
                fdf_file = open(data_file, "wb")
                fdf_file.write(fdf)
                fdf_file.close()

                sh.pdftk(vorlage, "fill_form", data_file, "output",
                         output_file, "flatten")

                pdfs.append(output_file)

                seite += 1

    return pdfs
Example #48
0
def write_pdf(source, fields, output, flatten=False):
    '''
    Take a source file path, list or dictionary of fdf fields, and
    output path, and create a filled-out pdf.
    '''
    fdf = forge_fdf(fdf_data_strings=fields)
    with NamedTemporaryFile(delete=False) as file:
        file.write(fdf)
    call = ['pdftk', source, 'fill_form', file.name, 'output', output]
    if flatten:
        call.append('flatten')
    try:
        check_output(call)
    except FileNotFoundError:
        raise PdftkNotInstalledError('Could not locate PDFtk installation')
    remove(file.name)
Example #49
0
def fill_template(template, data_strings=[], data_names=[], hidden=[], readonly=[], pdf_url=""):
    fdf = fdfgen.forge_fdf(pdf_url, data_strings, data_names, hidden, readonly)
    fdf_file = tempfile.NamedTemporaryFile(mode="wb", suffix=".fdf", delete=False)
    fdf_file.write(fdf)
    fdf_file.close()
    pdf_file = tempfile.NamedTemporaryFile(mode="wb", suffix=".pdf", delete=False)
    subprocess_arguments = [PDFTK_PATH, template, "fill_form", fdf_file.name, "output", pdf_file.name, "flatten"]
    result = call(subprocess_arguments)
    if result != 0:
        logmessage("Failed to fill PDF form " + str(template))
        raise DAError(
            "Call to pdftk failed for template "
            + str(template)
            + " where arguments were "
            + " ".join(subprocess_arguments)
        )
    return pdf_file.name
Example #50
0
    def exec_pdftk(self, data):
        fdf = forge_fdf("", data.items(), [], [], [])
        args = [
            "pdftk",
            self.filename,
            "fill_form", "-",
            "output", "-",
            "dont_ask",
            "flatten"
        ]

        p = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE)
        stdout, stderr = p.communicate(fdf)
        if stderr.strip():
            raise IOError(stderr)

        return StringIO.StringIO(stdout)
Example #51
0
def form_fill(fields):
	global pdf_pages
	# pprint(fields)
	fdf = forge_fdf("",fields,[],[],[])
	fdf_file = open(tmp_file,"w")
	fdf_file.write(fdf)
	fdf_file.close()
	output_file = '{0}{1}_{2}.pdf'.format(temp_folder, filename_prefix, fields[0][1])
	
	if pdf_pages == "":
		pdf_pages = output_file
	else:
		pdf_pages = pdf_pages + " " + output_file

	cmd = 'pdftk "{0}" fill_form "{1}" output "{2}" dont_ask'.format(pdf_file, tmp_file, output_file)
	os.system(cmd)
	os.remove(tmp_file)
Example #52
0
def autofillPDF(pdfPath,fields):
	env = envUtils.getEnvironment()
	formout = env.createGeneratedOutputFilePath('file_', '.pdf')
	try:
		pdftkBinaryPath = env.getPDFtkBinPath()
		fdf_data = fdfgen.forge_fdf("", fields, [], [], [])
		fdf_file_path = env.createGeneratedOutputFilePath('file_', '.fdf')
		fdf_file = open(fdf_file_path,"w")
		fdf_file.write(fdf_data)
		fdf_file.close()
		pdftk_cmd = "%s %s fill_form %s output %s" % (pdftkBinaryPath,pdfPath,fdf_file_path,formout)
		error = os.system(pdftk_cmd)
		if error <> 0:
			formout = pdfPath
	except Exception,e:
		#if the form won't autofill, eat the error and return the original form
		formout = pdfPath
		pass
Example #53
0
def generate_fdf():
    
    # TODO: use session ID instead of max ID
    f = model1040NREZ.objects.all().order_by("-id")[0]
	
    fields = [('topmostSubform[0].Page1[0].f1_01_0_[0]', f.INFOL01),
            ('topmostSubform[0].Page1[0].f1_02_0_[0]', f.INFOL02), 
             ('topmostSubform[0].Page1[0].f1_10_0_[0]', f.F1040NREZL03), 
             ('topmostSubform[0].Page1[0].f1_12_0_[0]', f.F1040NREZL04), 
             ('topmostSubform[0].Page1[0].f1_14_0_[0]', f.F1040NREZL05), 
             ('topmostSubform[0].Page1[0].f1_16_0_[0]', f.F1040NREZL06), 
            ('topmostSubform[0].Page1[0].f1_18_0_[0]', f.F1040NREZL07)]    
            
    fdf = forge_fdf("",fields,[],[],[])
    # TODO: include session ID in fdf file
    fdf_file = open("data.fdf","w")
    fdf_file.write(fdf)
    fdf_file.close()
Example #54
0
    def fill_form(self, fields, src, pdftk_bin=None):
        if pdftk_bin is None:
            from django.conf import settings

            assert hasattr(
                settings, "PDFTK_BIN"
            ), "PDF generation requires pdftk (http://www.pdflabs.com/tools/pdftk-the-pdf-toolkit/). Edit your PDFTK_BIN settings accordingly."
            pdftk_bin = settings.PDFTK_BIN

        fdf_stream = forge_fdf(fdf_data_strings=fields)

        cmd = [pdftk_bin, src, "fill_form", "-", "output", "-", "flatten"]
        cmd = " ".join(cmd)

        try:
            process = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
            return process.communicate(input=fdf_stream)
        except OSError, e:
            return None, e
Example #55
0
def actas_compromiso(modeladmin, request, queryset):
    evidencia = Evidencia.objects.filter(entregable__id__in = [8,72,127]).values_list('beneficiarios_cargados__id',flat=True).distinct()
    x = list(evidencia)
    x.remove(None)
    for formador in queryset:
        for beneficiario in Beneficiario.objects.filter(formador = formador).exclude(id__in = x):

            municipio = ''
            sede = ''

            if beneficiario.radicado != None:
                municipio = beneficiario.radicado.municipio.nombre.upper()
                sede = beneficiario.radicado.nombre_sede.upper()
            else:
                municipio = beneficiario.municipio_text.upper()
                if beneficiario.sede_text != None:
                    sede = beneficiario.sede_text.upper()

            fields = [('Texto1', beneficiario.get_full_name().upper()),
                      ('Texto2', beneficiario.cedula),
                      ('Texto3', municipio),
                      ('Texto4', sede),
                      ('Texto5', formador.get_full_name().upper()),
                      ('Texto6', formador.cedula),
                      ('Texto7', formador.expedicion.upper()),
                      ('Texto8', 'ASOANDES'),
                      ('Texto9', beneficiario.diplomado.nombre.upper()),
                      ('Texto10', municipio.upper()),
                      ('Texto11', random.randint(15,31)),
                      ('Texto12', 'AGOSTO'),
            ]

            fdf = forge_fdf("",fields,[],[],[])

            if not os.path.exists("C:\\Temp\\ACTAS\\"+ formador.get_full_name().upper().encode('ascii',errors='ignore')):
                os.mkdir("C:\\Temp\\ACTAS\\"+ formador.get_full_name().upper().encode('ascii',errors='ignore'))

            fdf_file = open("C:\\Temp\\ACTAS\\"+ formador.get_full_name().upper().encode('ascii',errors='ignore') +"\\"+str(beneficiario.cedula)+".fdf","wb")
            fdf_file.write(fdf)
            fdf_file.close()
            os.system('pdftk "C:\\Temp\\ACTAS\\Acta de compromiso.pdf" fill_form "C:\\Temp\\ACTAS\\'+ formador.get_full_name().upper().encode('ascii',errors='ignore') + "\\" + str(beneficiario.cedula)+'.fdf" output "C:\\Temp\\ACTAS\\' + formador.get_full_name().upper().encode('ascii',errors='ignore') + "\\" + str(beneficiario.cedula)+'.pdf" flatten')
            os.remove('C:\\Temp\\ACTAS\\'+ formador.get_full_name().upper().encode('ascii',errors='ignore') + "\\" + str(beneficiario.cedula)+'.fdf')
Example #56
0
def fill_w10(form, data):
  # print "data", data
  inputs = formencode.variabledecode.variable_decode(data)
  # print "inputs", inputs
  fields = populate_fields(form, inputs)
  # print "FIELDS"
  # print fields
  # fields = [
  #   ('topmostSubform[0].Page1[0].p1-t1[0]', inputs['inputs[0][value]']),
  #   ('topmostSubform[0].Page1[0].p1-t2[0]', inputs['inputs[1][value]']),
  #   ('topmostSubform[0].Page1[0].p1-t3[0]', inputs['inputs[2][value]']),
  #   ('topmostSubform[0].Page1[0].p1-cb1[0]', inputs['inputs[3][value]']),
  #   ('topmostSubform[0].Page1[0].p1-t4[0]', inputs['inputs[4][value]']),
  #   ('topmostSubform[0].Page1[0].p1-t5[0]', inputs['inputs[5][value]']),
  # ]
  fdf = forge_fdf("",fields,[],[],[])
  fdf_file = open("data.fdf","wb")
  fdf_file.write(fdf)
  fdf_file.close()
  call(['pdftk pdfs/' + form + '.pdf fill_form data.fdf output pdfs/output.pdf flatten'], shell=True)
Example #57
0
    def save(self, path):
        fdf = fdfgen.forge_fdf('', self.fdf_fields, [], [], [])
        pages = [str(p) for p in self.pages]

        # TODO: the "cat" step breaks the JavaScript used to print
        # Georgia Form 600S, so we should just skip the step if the PDF
        # fails to specify a list of pages.

        stdout = run_pdftk(fdf, [
            self.original_pdf_path, 'fill_form', '-', 'output', '-', 'flatten'])
        stdout = run_pdftk(stdout, ['-', 'cat'] + pages + ['output', path])

        if not self.canvases:
            return

        with open(path, 'rb') as f:
            inputdata = f.read()
        pdf = PdfFileReader(StringIO(inputdata))

        output = PdfFileWriter()

        for i in range(pdf.numPages):
            page = pdf.getPage(i)
            canvas = self.canvases.get(i + 1)
            if canvas is not None:
                canvas.showPage()
                overlay = PdfFileReader(StringIO(canvas.getpdfdata()))
                page.mergePage(overlay.getPage(0))
            output.addPage(page)

        # We call write() outside of the open() context to avoid
        # truncating the file if write() dies with an exception.

        output_stream = StringIO()
        try:
            output.write(output_stream)
        except Exception as e:
            sys.stderr.write('PyPDF exception: {}\n'.format(e))
            sys.exit(1)
        with open(path, 'w') as f:
            f.write(output_stream.getvalue())
Example #58
0
def main():
    """Fill in each field in a PDF form with its own name."""

    path = sys.argv[1]
    data = subprocess.check_output(['pdftk', path, 'dump_data_fields'])
    with open('fields.txt', 'w') as f:
        f.write(data)

    names = [ line.split(' ', 1)[1] for line in data.splitlines()
              if line.startswith('FieldName: ') ]

    fields = [ (name, name.split('.')[-1]) for name in names ]
    # verbose: fields = [ (name, name) for name in names ]

    fdf = forge_fdf('', fields, [], [], [])
    fdf_file = open('data.fdf', 'w')
    fdf_file.write(fdf)
    fdf_file.close()

    subprocess.check_call(['pdftk', path, 'fill_form', 'data.fdf',
                           'output', 'fields.pdf'])
Example #59
0
def fillPDFForm(formPdf, fields, outputPdf="filled.pdf", input_is_fullpath=False, editable=False):
    """
        fill given pdf file with form fields with given attributes and store result in pdf file
    """
    # build data file
    fdffilename = "{}{}infdata.fdf".format(config.get('paths.tempdir'), str(random.random())[2:])
    outputPdf = "{}{}filled.pdf".format(config.get('paths.tempdir'), str(random.random())[2:])
    try:
        with open(fdffilename, 'wb') as fdf_file:
            fdf_file.write(fdfgen.forge_fdf(fdf_data_strings=fields))

        # fill data in form pdf and generate pdf
        pdftkcmd = ["pdftk", formPdf, "fill_form", fdffilename, "output", outputPdf]
        if not editable:
            pdftkcmd.append("flatten")
        utils.process.call(pdftkcmd)

        if os.path.exists(fdffilename):
            os.remove(fdffilename)
    except Exception:
        logg.exception("exception in workflow step addformpage, error while filling pdf form, ignoring")

    return outputPdf if os.path.exists(outputPdf) else ""  # check if file created
Example #60
0
def generate(request):
    form = DockerfileRequestForm(request.POST)
    if request.method == 'POST' and form.is_valid():
        data = form.cleaned_data["character_sheet"]
        conv = Converter()
        char = conv.convert(data)

        pdf_file = tempfile.NamedTemporaryFile("wb", delete=False)
        pdf_file.close()
        os.unlink(pdf_file.name)
        if request.POST["target"] == "sheet":
            fields = fill_pdf(char)
            fdf = forge_fdf("", fields, [], [], [])
            fdf_file = tempfile.NamedTemporaryFile("wb", delete=False)
            fdf_file.write(fdf)
            fdf_file.close()

            subprocess.call(["pdftk", "dndgen/Interactive_DnD_4.0_Character_Sheet.pdf",
                             "fill_form", fdf_file.name, "output", pdf_file.name, "flatten"])
            os.unlink(fdf_file.name)

            response_file = open(pdf_file.name, 'rb')
            wrapper = FileWrapper(response_file)
            response = HttpResponse(wrapper, content_type='application/pdf')
            response['Content-Disposition'] = 'attachment; filename="sheet.pdf"'
            response['Content-Length'] = os.path.getsize(pdf_file.name)
            return response
        if request.POST["target"] == "powers":
            gen(char, pdf_file.name)
            response_file = open(pdf_file.name, 'rb')
            wrapper = FileWrapper(response_file)
            response = HttpResponse(wrapper, content_type='application/pdf')
            response['Content-Disposition'] = 'attachment; filename="powers.pdf"'
            response['Content-Length'] = os.path.getsize(pdf_file.name)
            return response
    else:
        return render(request, "index.html", {'form': form})