コード例 #1
0
ファイル: PDF.py プロジェクト: mdp/rpaframework
    def update_field_values(self,
                            source_pdf: str = None,
                            target_pdf: str = None,
                            newvals: dict = None) -> None:
        """Update field values in PDF if it has fields.

        :param source_pdf: source PDF with fields to update
        :param target_pdf: updated target PDF
        :param newvals: dictionary with key values to update
        """
        self.switch_to_pdf_document(source_pdf)
        reader = PyPDF2.PdfFileReader(self.active_fileobject, strict=False)
        if "/AcroForm" in reader.trailer["/Root"]:
            reader.trailer["/Root"]["/AcroForm"].update(
                {NameObject("/NeedAppearances"): BooleanObject(True)})
        writer = PdfFileWriter()
        writer.cloneDocumentFromReader(reader)

        for i in range(reader.getNumPages()):
            page = reader.getPage(i)
            try:
                if newvals:
                    self.logger.debug("Updating form field values for page %s",
                                      i)
                    writer.updatePageFormFieldValues(page, newvals)
                else:
                    writer.updatePageFormFieldValues(
                        page,
                        {
                            k: f"#{i} {k}={v}"
                            for i, (k, v) in enumerate(
                                reader.getFormTextFields().items())
                        },
                    )
                writer.addPage(page)
            except Exception as e:  # pylint: disable=W0703
                self.logger.warning(repr(e))
                writer.addPage(page)

        if target_pdf is None:
            target_pdf = self.active_pdf
        with open(target_pdf, "wb") as f:
            writer.write(f)
コード例 #2
0
ファイル: reader.py プロジェクト: supracd/law2go
def set_need_appearances_writer(writer):
    # See 12.7.2 and 7.7.2 for more information: http://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/PDF32000_2008.pdf
    try:
        catalog = writer._root_object
        # get the AcroForm tree
        if "/AcroForm" not in catalog:
            writer._root_object.update({
                NameObject("/AcroForm"):
                IndirectObject(len(writer._objects), 0, writer)
            })

        need_appearances = NameObject("/NeedAppearances")
        writer._root_object["/AcroForm"][need_appearances] = BooleanObject(
            True)
        return writer

    except Exception as e:
        print('set_need_appearances_writer() catch : ', repr(e))
        return writer
コード例 #3
0
def set_need_appearances_writer(writer):
    # basically used to ensured there are not
    # overlapping form fields, which makes printing hard
    try:
        catalog = writer._root_object
        # get the AcroForm tree and add "/NeedAppearances attribute
        if "/AcroForm" not in catalog:
            writer._root_object.update({
                NameObject("/AcroForm"):
                IndirectObject(len(writer._objects), 0, writer)
            })

        need_appearances = NameObject("/NeedAppearances")
        writer._root_object["/AcroForm"][need_appearances] = BooleanObject(
            True)

    except Exception as e:
        print('set_need_appearances_writer() catch : ', repr(e))

    return writer
コード例 #4
0
    def set_need_appearances_writer(self, writer):
        """
        Funzione usata dalla get_export_pdf per generare il report
        precompilato dell'AdE liquidazione periodica IVA
        """
        try:
            catalog = writer._root_object
            # get the AcroForm tree
            if "/AcroForm" not in catalog:
                writer._root_object.update({
                    NameObject("/AcroForm"):
                    IndirectObject(len(writer._objects), 0, writer)
                })

            need_appearances = NameObject("/NeedAppearances")
            writer._root_object["/AcroForm"][need_appearances] = BooleanObject(
                True)
            return writer

        except Exception as e:
            print('set_need_appearances_writer() catch : ', repr(e))
            return writer
コード例 #5
0
    def _merge_pdfs(self, in_dir, out_file):
        """Merges PDFs in a given directory and outputs it to a single PDF file.
        If `same_page_number` is set to true in the config file, all tests will have `max_pages` number of pages.
        
        Parameters:
            in_dir (str): Path to the input directory containing the PDF files to be merged.
            out_file (str): Path to the merged PDF.
        """
        pw = PdfFileWriter()

        firstPDF = True
        for f in sorted(listdir(in_dir)):
            if isfile(join(in_dir, f)) and regex.match(
                    '^test.*\.pdf$', f, flags=regex.IGNORECASE):
                pr = PdfFileReader(join(in_dir, f), strict=False)

                form = pr.trailer["/Root"][
                    "/AcroForm"]  # see: https://stackoverflow.com/questions/47288578/pdf-form-filled-with-pypdf2-does-not-show-in-print

                pw.appendPagesFromReader(pr)
                if self.config['same_page_number'] and pr.getNumPages(
                ) < self.config['max_pages']:
                    for i in range(self.config['max_pages'] -
                                   pr.getNumPages()):  # pylint: disable=unused-variable
                        pw.addBlankPage()

                if firstPDF:
                    pw._root_object.update({NameObject("/AcroForm"): form})
                    firstPDF = False
                else:
                    pw._root_object["/AcroForm"]["/Fields"].extend(
                        form["/Fields"])

        pw._root_object["/AcroForm"].update(
            {NameObject("/NeedAppearances"): BooleanObject(True)})

        f = codecs.open(out_file, 'wb')
        pw.write(f)
        f.close()
コード例 #6
0
ファイル: PDF.py プロジェクト: mcspx/rpaframework
    def _set_need_appearances_writer(self, writer: PdfFileWriter):
        # See 12.7.2 and 7.7.2 for more information:
        # http://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/PDF32000_2008.pdf
        try:
            catalog = writer._root_object  # pylint: disable=W0212
            # get the AcroForm tree
            if "/AcroForm" not in catalog:
                catalog.update({
                    NameObject("/AcroForm"):
                    IndirectObject(
                        len(writer._objects),
                        0,
                        writer  # pylint: disable=W0212
                    )
                })

            need_appearances = NameObject("/NeedAppearances")
            catalog["/AcroForm"][need_appearances] = BooleanObject(True)
            # del writer._root_object["/AcroForm"]['NeedAppearances']
            return writer

        except Exception as e:  # pylint: disable=broad-except
            print("set_need_appearances_writer() catch : ", repr(e))
            return writer
コード例 #7
0
def readPDFwApp(infile):
    read_pdf = PdfFileReader(open(infile, "rb"), strict=False)
    if "/AcroForm" in read_pdf.trailer["/Root"]:
        read_pdf.trailer["/Root"]["/AcroForm"].update(
            {NameObject("/NeedAppearances"): BooleanObject(True)})
    return read_pdf
コード例 #8
0
def test_boolean_object_exception():
    stream = BytesIO(b"False")
    with pytest.raises(PdfReadError) as exc:
        BooleanObject.read_from_stream(stream)
    assert exc.value.args[0] == "Could not read Boolean object"
コード例 #9
0
def test_boolean_object_write():
    stream = BytesIO()
    boolobj = BooleanObject(None)
    boolobj.write_to_stream(stream, encryption_key=None)
    stream.seek(0, 0)
    assert stream.read() == b"false"
コード例 #10
0
def annotate(fp_in, annotations):
    reader = PdfFileReader(fp_in)
    pdf = PdfFileWriter()
    for page in reader.pages:
        pdf.addPage(page)

    for annotation in annotations:
        page = annotation.get('page', 0)
        try:
            pdfpage = pdf.getPage(page)
        except IndexError:
            print >> sys.stderr, 'Page %d not found in pdf, not adding annotations %r' % (
                page, annotation)
            continue

        size = pdfpage.mediaBox
        angle = int(pdfpage.get('/Rotate', 0))
        x = annotation['x']
        y = annotation['y']
        if angle == 0:
            x = float(x)
            y = size[3] - float(y) - 20
        elif angle == 90:
            x, y = float(y) - 2, float(x) - 15
        else:
            x = float(x)
            y = float(y)
            print >> sys.stderr, 'Page rotated by %d degrees not implemented yet' % (
                angle)

        color = annotation.get('color', None)
        if isinstance(color, basestring):
            if color[:1] != '#':
                print >> sys.stderr, 'Unsupported color format: %s' % (color)
                color = None
            else:
                # Assume HTML color with format "#RRGGBB".
                try:
                    color = int(color[1:], 16)
                except ValueError as e:
                    print >> sys.stderr, 'Unsupported color format: %s (%s)' % (
                        color, e)
                    color = None

        if color is not None:
            r, g, b = color >> 16, (color >> 8) & 0xff, color & 0xff
            color = (r * BYTE_TO_COLOR, g * BYTE_TO_COLOR, b * BYTE_TO_COLOR)
        else:
            color = None

        pages = pdf.getObject(pdf._pages)
        pageref = pages["/Kids"][page]

        anno = DictionaryObject()
        anno.update({
            NameObject('/Type'):
            NameObject('/Annot'),
            NameObject('/Subtype'):
            NameObject('/Text'),
            NameObject('/P'):
            pageref,
            NameObject('/Rect'):
            RectangleObject([x, y, x + 18, y + 20]),
            NameObject('/Contents'):
            TextStringObject(annotation['text']),
            NameObject('/C'):
            ArrayObject([FloatObject(x) for x in color]),
            NameObject('/Open'):
            BooleanObject(True),
        })
        author = annotation.get('author', None)
        if author:
            anno[NameObject('/T')] = TextStringObject(author)
        modified = annotation.get('modified', None)
        if modified:
            modified = time.strftime('%Y%m%d%H%M%SZ', time.gmtime(modified))
            anno[NameObject('/M')] = TextStringObject(modified)

        annoRef = pdf._addObject(anno)
        annots = pdfpage.get('/Annots', None)
        if annots is None:
            annots = pdfpage[NameObject('/Annots')] = ArrayObject([annoRef])
        else:
            annots.append(annoRef)

    fp_out = StringIO()
    pdf.write(fp_out)
    return fp_out.getvalue()
コード例 #11
0
from io import BytesIO
import PyPDF2
from PyPDF2.generic import BooleanObject, NameObject, IndirectObject, NumberObject

# open the pdf
input_stream = open("YourPDF.pdf", "rb")
pdf_reader = PyPDF2.PdfFileReader(input_stream, strict=False)
if "/AcroForm" in pdf_reader.trailer["/Root"]:
    pdf_reader.trailer["/Root"]["/AcroForm"].update(
        {NameObject("/NeedAppearances"): BooleanObject(True)})

pdf_writer = PyPDF2.PdfFileWriter()
set_need_appearances_writer(pdf_writer)
if "/AcroForm" in pdf_writer._root_object:
    # Acro form is form field, set needs appearances to fix printing issues
    pdf_writer._root_object["/AcroForm"].update(
        {NameObject("/NeedAppearances"): BooleanObject(True)})

data_dict = dict()  # this is a dict of your DB form values

pdf_writer.addPage(pdf_reader.getPage(0))
page = pdf_writer.getPage(0)
# update form fields
pdf_writer.updatePageFormFieldValues(page, data_dict)
for j in range(0, len(page['/Annots'])):
    writer_annot = page['/Annots'][j].getObject()
    for field in data_dict:
        if writer_annot.get('/T') == field:
            writer_annot.update({
                NameObject("/Ff"): NumberObject(1)  # make ReadOnly
            })
コード例 #12
0
ファイル: reports.py プロジェクト: VegaAISolutions/VegaTax
def create_irs_form(session, taxYear=2017):
    newFileName = '{}8929_2017_test.pdf'.format(taxreport_base)
    x = PdfFileReader(open('{}f8949_template.pdf'.format(taxreport_base),
                           'rb'))
    if "/AcroForm" in x.trailer["/Root"]:
        x.trailer["/Root"]["/AcroForm"].update(
            {NameObject("/NeedAppearances"): BooleanObject(True)})

    output = PdfFileWriter()
    if "/AcroForm" in output._root_object:
        output._root_object["/AcroForm"].update(
            {NameObject("/NeedAppearances"): BooleanObject(True)})
    descr_index = 3
    dacq_index = 4
    dsold_index = 5
    proceeds_index = 6
    cost_index = 7
    codes_index = 8
    adjust_index = 9
    gainloss_index = 10
    page_index = 0
    page_header_index = 1
    for row in session.query(Transactions).filter(
            Transactions.Action == 'SELL'):
        y = datetime.strptime(row.Date, '%m/%d/%Y%H:%M:%S').year
        term = ''
        if y >= taxYear:
            page_index = 0
            page_header_index = 1
        else:
            page_index = 1
            page_header_index = 2

        gainloss = 0.0
        if row.Action == 'SELL':
            gainloss = row.Price + row.Cost
        fields = ({
            'f' + str(page_header_index) + '_' + str(descr_index) + '[0]':
            str(row.Volume) + ' ' + row.Coin,  #Description
            'f' + str(page_header_index) + '_' + str(dacq_index) + '[0]':
            str(row.Date),  #Date Acquired
            'f' + str(page_header_index) + '_' + str(dsold_index) + '[0]':
            str(row.DateSold),  #Date Sold (c)
            'f' + str(page_header_index) + '_' + str(proceeds_index) + '[0]':
            str(row.Price),  #Proceeds (d)
            'f' + str(page_header_index) + '_' + str(cost_index) + '[0]':
            str(row.Cost),  #Cost Basis(e)
            'f' + str(page_header_index) + '_' + str(codes_index) + '[0]':
            '0',  # codes
            'f' + str(page_header_index) + '_' + str(adjust_index) + '[0]':
            '0',  # adjust
            'f' + str(page_header_index) + '_' + str(gainloss_index) + '[0]':
            str(gainloss),  #Gain or loss(h)
        })
        print('Fields')
        print(fields)
        page = x.getPage(page_index)
        output.addPage(page)
        output.updatePageFormFieldValues(page, fields)
        descr_index += 8
        dacq_index += 8
        dsold_index += 8
        proceeds_index += 8
        cost_index += 8
        codes_index += 8
        adjust_index += 8
        gainloss_index += 8
    newObject = open(newFileName, 'wb')
    output.write(newObject)
    newObject.close()
コード例 #13
0
def print_f99():
    """
    This function is being invoked internally from controllers
    HTTP request needs to have form_type, file, and attachment_file
    form_type : F99
    json_file: please refer to below sample JSON
    attachment_file: It is a PDF file that will be merged to the generated PDF file.
    sample:
    {
    "REASON_TYPE":"MST",
    "COMMITTEE_NAME":"DONALD J. TRUMP FOR PRESIDENT, INC.",
    "FILER_FEC_ID_NUMBER":"C00580100",
    "IMGNO":"201812179143565008",
    "FILING_TIMESTAMP":"12/17/2018 17 : 09",
    "STREET_1":"725 FIFTH AVENUE",
    "STREET_2":"",
    "CITY":"NEW YORK",
    "STATE":"NY",
    "ZIP":"10022",
    "TREASURER_FULL_NAME":"CRATE, BRADLEY, , ,",
    "TREASURER_NAME":"CRATE, BRADLEY, , ,",
    "EF_STAMP":"[Electronically Filed]",
    "DATE_SIGNED_MM":"01",
    "DATE_SIGNED_DD":"28",
    "DATE_SIGNED_YY":"2019",
    "MISCELLANEOUS_TEXT":"This statement is in response to the Commission's letter to the Committee
                            dated November 12, 2018, regarding two items related to the
                            above-referenced report ('the Original Report')."
    }
    :return: return JSON response
    sample:
    {
    "message": "",
    "results": {
        "file_name": "bd78435a70a70d656145dae89e0e22bb.pdf",
        "file_url": "https://fecfile-dev-components.s3.amazonaws.com/output/bd78435a70a70d656145dae89e0e22bb.pdf"
    },
    "success": "true"
    }
    """
    if 'json_file' in request.files:
        json_file = request.files.get('json_file')
        json_file_md5 = utils.md5_for_file(json_file)
        json_file.stream.seek(0)

        infile = current_app.config['FORM_TEMPLATES_LOCATION'].format('F99')
        json_file.save(
            current_app.config['REQUEST_FILE_LOCATION'].format(json_file_md5))
        outfile = current_app.config['OUTPUT_FILE_LOCATION'].format(
            json_file_md5)

        json_data = json.load(
            open(current_app.config['REQUEST_FILE_LOCATION'].format(
                json_file_md5)))

        # json_data['FILER_FEC_ID_NUMBER'] = json_data['FILER_FEC_ID_NUMBER'][1:]

        if json_data['REASON_TYPE'] == 'MST':
            reason_type_data = {"REASON_TYPE_MST": "/MST"}

        if json_data['REASON_TYPE'] == 'MSM':
            reason_type_data = {"REASON_TYPE_MSM": "/MSM"}

        if json_data['REASON_TYPE'] == 'MSI':
            reason_type_data = {"REASON_TYPE_MSI": "/MSI"}

        if json_data['REASON_TYPE'] == 'MSW':
            reason_type_data = {"REASON_TYPE_MSW": "/MSW"}
        # open the input file

        input_stream = open(infile, "rb")

        pdf_reader = PdfFileReader(input_stream, strict=True)

        if "/AcroForm" in pdf_reader.trailer["/Root"]:
            pdf_reader.trailer["/Root"]["/AcroForm"].update(
                {NameObject("/NeedAppearances"): BooleanObject(True)})

        pdf_writer = PdfFileWriter()

        form.set_need_appearances_writer(pdf_writer)

        if "/AcroForm" in pdf_writer._root_object:
            pdf_writer._root_object["/AcroForm"].update(
                {NameObject("/NeedAppearances"): BooleanObject(True)})

        for page_num in range(pdf_reader.numPages):
            page_obj = pdf_reader.getPage(page_num)

            pdf_writer.addPage(page_obj)

            form.update_checkbox_values(page_obj, reason_type_data)

            pdf_writer.updatePageFormFieldValues(page_obj, json_data)

        # Add the F99 attachment
        if 'attachment_file' in request.files:
            # reading Attachment title file
            attachment_title_file = current_app.config[
                'FORM_TEMPLATES_LOCATION'].format('Attachment_Title')
            attachment_title_stream = open(attachment_title_file, "rb")
            attachment_title_reader = PdfFileReader(attachment_title_stream,
                                                    strict=True)
            attachment_stream = request.files.get('attachment_file')
            attachment_reader = PdfFileReader(attachment_stream, strict=True)

            for attachment_page_num in range(attachment_reader.numPages):
                attachment_page_obj = attachment_reader.getPage(
                    attachment_page_num)
                if attachment_page_num == 0:
                    attachment_page_obj.mergePage(
                        attachment_title_reader.getPage(0))

                pdf_writer.addPage(attachment_page_obj)

        output_stream = open(outfile, "wb")

        pdf_writer.write(output_stream)

        input_stream.close()

        output_stream.close()

        # push output file to AWS
        s3 = boto3.client('s3')
        s3.upload_file(
            outfile,
            current_app.config['AWS_FECFILE_COMPONENTS_BUCKET_NAME'],
            current_app.config['OUTPUT_FILE_LOCATION'].format(json_file_md5),
            ExtraArgs={
                'ContentType': "application/pdf",
                'ACL': "public-read"
            })

        response = {
            # 'file_name': '{}.pdf'.format(json_file_md5),
            'pdf_url':
            current_app.config['PRINT_OUTPUT_FILE_URL'].format(json_file_md5)
        }

        if flask.request.method == "POST":
            envelope = common.get_return_envelope(data=response)
            status_code = status.HTTP_201_CREATED
            return flask.jsonify(**envelope), status_code
    else:

        if flask.request.method == "POST":
            envelope = common.get_return_envelope(
                'false', 'JSON file is missing from your request')
            status_code = status.HTTP_400_BAD_REQUEST
            return flask.jsonify(**envelope), status_code
コード例 #14
0
 def __init__(self, infile):
     self.pdf = PdfFileReader(open(infile, "rb"), strict=False)
     if "/AcroForm" in self.pdf.trailer["/Root"]:
         self.pdf.trailer["/Root"]["/AcroForm"].update(
             {NameObject("/NeedAppearances"): BooleanObject(True)})
コード例 #15
0
def compila_atto_notorio(request, id, dichiarazione_check_std=False, dichiarazione_check_pers=False):
    moduli_input_path = os.path.join(settings.STATIC_ROOT, 'RimborsiApp', 'moduli')
    moduli_output_path = os.path.join(settings.MEDIA_ROOT, 'moduli')
    missione = Missione.objects.get(user=request.user, id=id)
    input_file = os.path.join(moduli_input_path, 'dichiarazione_atto_notorieta.pdf')
    modulo_missione = ModuliMissione.objects.get(missione=missione)

    # open the pdf
    input_stream = open(input_file, "rb")
    pdf_reader = PdfFileReader(input_stream, strict=False)
    if "/AcroForm" in pdf_reader.trailer["/Root"]:
        pdf_reader.trailer["/Root"]["/AcroForm"].update({NameObject("/NeedAppearances"): BooleanObject(True)})

    pdf_writer = PdfFileWriter()
    set_need_appearances_writer(pdf_writer)
    if "/AcroForm" in pdf_writer._root_object:
        # Acro form is form field, set needs appearances to fix printing issues
        pdf_writer._root_object["/AcroForm"].update({NameObject("/NeedAppearances"): BooleanObject(True)})

    dichiarazione = ''
    if dichiarazione_check_std:
        dichiarazione += f'Di essersi recato a {missione.citta_destinazione} - {missione.stato_destinazione.nome} dal' \
                         f' {missione.inizio.strftime("%d/%m/%Y")} al {missione.fine.strftime("%d/%m/%Y")}' \
                         f' per {missione.motivazione}.'
    if dichiarazione_check_pers:
        dichiarazione += f' {modulo_missione.atto_notorio_dichiarazione}'

    if missione.user.profile.straniero:
        luogo_nascita = missione.user.profile.luogo_nascita_straniero
        provincia_nascita = ''
        residenza_comune = missione.user.profile.residenza.comune_straniero
        residenza_provincia = missione.user.profile.residenza.provincia_straniero
        domicilio_comune = missione.user.profile.domicilio.comune_straniero
        domicilio_provincia = missione.user.profile.domicilio.provincia_straniero
    else:
        luogo_nascita = missione.user.profile.luogo_nascita.name
        provincia_nascita = missione.user.profile.luogo_nascita.provincia.codice_targa
        residenza_comune = missione.user.profile.residenza.comune.name
        residenza_provincia = missione.user.profile.residenza.provincia.codice_targa
        domicilio_comune = missione.user.profile.domicilio.comune.name
        domicilio_provincia = missione.user.profile.domicilio.provincia.codice_targa

    data_dict = {
        '1': missione.user.last_name,
        '2': missione.user.first_name,
        # '3': missione.user.profile.luogo_nascita.name,
        '3': luogo_nascita,
        # '4': missione.user.profile.luogo_nascita.provincia.codice_targa,
        '4': provincia_nascita,
        '5': missione.user.profile.data_nascita.strftime('%d/%m/%Y'),
        # '6': missione.user.profile.residenza.comune.name,
        '6': residenza_comune,
        # '7': missione.user.profile.residenza.provincia.codice_targa,
        '7': residenza_provincia,
        '8': missione.user.profile.residenza.via,
        '9': missione.user.profile.residenza.n,
        # '10': missione.user.profile.domicilio.comune.name,
        '10': domicilio_comune,
        # '11': missione.user.profile.domicilio.provincia.codice_targa,
        '11': domicilio_provincia,
        '12': missione.user.profile.domicilio.via,
        '13': missione.user.profile.domicilio.n,
        '14': dichiarazione,
        '20': f'Modena, {modulo_missione.atto_notorio.strftime("%d/%m/%Y")}',
    }

    pdf_writer.addPage(pdf_reader.getPage(0))
    page = pdf_writer.getPage(0)
    pdf_writer.updatePageFormFieldValues(page, data_dict)

    # Disable the fillable fields
    # for j in range(0, len(page['/Annots'])):
    #     writer_annot = page['/Annots'][j].getObject()
    #     writer_annot.update({NameObject("/Ff"): NumberObject(1)})

    output_name_tmp = os.path.join(moduli_output_path, f'Missione_{missione.id}_atto_notorio_tmp.pdf')
    outputStream = open(output_name_tmp, "wb")
    pdf_writer.write(outputStream)
    outputStream.close()

    # Salvo il pdf appena creato dentro a un FileField
    output_name = f'Missione_{missione.id}_atto_notorio.pdf'
    outputStream = open(output_name_tmp, "rb")
    modulo_missione.atto_notorio_file.save(output_name, outputStream)

    # Elimino il file temporaneo
    os.remove(output_name_tmp)
コード例 #16
0
def create_annotation(x, y, meta):
    color = [255.0 / 255.0, 209 / 255.0, 0]
    # link
    linkAnnotation = DictionaryObject()
    # https://www.adobe.com/content/dam/acom/en/devnet/pdf/pdfs/PDF32000_2008.pdf
    linkAnnotation.update({
        # Table 165 NoZoom
        NameObject("/F"):
        NumberObject(4),
        NameObject("/Type"):
        NameObject("/Annot"),
        NameObject("/Subtype"):
        NameObject("/Link"),

        # Table 164 color, annotation rectangle
        NameObject("/C"):
        ArrayObject([FloatObject(c) for c in color]),
        NameObject("/Rect"):
        ArrayObject([
            FloatObject(x),
            FloatObject(y),
            FloatObject(x + 20),
            FloatObject(y + 20)
        ]),

        # Table 173 link annotation
        NameObject('/A'):
        DictionaryObject({
            # Table 206 uri
            NameObject('/S'): NameObject('/URI'),
            NameObject('/URI'): TextStringObject(meta["contents"])
        }),
        # Table 173 invert rect when mouse
        NameObject('/H'):
        NameObject('/I'),
        # table 164 hor corner radius, vert corner radius, border width
        # dash array table 56
        NameObject('/Border'):
        ArrayObject([
            NameObject(0),
            NameObject(0),
            NameObject(5),
        ]),
    })

    commentAnnotation = DictionaryObject()
    # https://www.adobe.com/content/dam/acom/en/devnet/pdf/pdfs/PDF32000_2008.pdf
    commentAnnotation.update({
        # Table 165 NoZoom
        NameObject("/F"):
        NumberObject(4),
        NameObject("/Type"):
        NameObject("/Annot"),
        NameObject("/Subtype"):
        NameObject("/Text"),

        # Table 170 titlebar
        NameObject("/T"):
        TextStringObject(meta["author"]),
        NameObject("/Contents"):
        TextStringObject(meta["contents"]),

        # Table 164 color, annotation rectangle
        NameObject("/C"):
        ArrayObject([FloatObject(c) for c in color]),
        NameObject("/Rect"):
        ArrayObject([
            FloatObject(x),
            FloatObject(y),
            FloatObject(x + 5),
            FloatObject(y + 5)
        ]),

        # 12.5.6.4 text annotation
        NameObject('/Open'):
        BooleanObject(False),
        NameObject('/Name'):
        NameObject('/Comment'),
    })

    return linkAnnotation, commentAnnotation
コード例 #17
0
    def draw_rectangles_for_solution(self, f_in, f_out, solution, points):
        """Drawing green filled rectangles near the correct answers for every problem,
        in order to indicate the correct solution.
        It calculates and writes the total score achieved too.
        
        Parameters:
            f_in (str): Path to the input PDF file.
            f_out (str): Path to the output PDF file.
            solution (dict): The solution (correct answers) corresponding to the input PDF file (f_in).
            points (float): Total points achieved.
        """
        pr = PdfFileReader(f_in)
        dest = pr.getNamedDestinations()
        fields = pr.getFields()

        # """IT IS NOT WORKING IF THIS COMES FIRST:"""
        #         a = PdfAnnotator(f_in)
        #         for p in range(pr.getNumPages()):
        #             for dk, dv in dest.items():
        #                 if pr.getDestinationPageNumber(dv) == p and dk.startswith('ht_'):
        #                     inds = [int(ind) for ind in dk[3:].split(':')]
        # #                     if inds[2] in solution[inds[1]][1]:
        #                     if inds[4] in solution[inds[1]][1]:
        #                         # using some hard-coded values:
        #                         a.add_annotation('square',
        #                                          Location(x1=float(dv['/Left']), y1=float(dv['/Top']), x2=float(dv['/Left'])+5, y2=float(dv['/Top'])+5, page=p),
        #                                          Appearance(stroke_color=(0, 1, 0), stroke_width=5),)
        #         a.write(f_out)

        pw = PdfFileWriter()
        #         pr = PdfFileReader(f_out, strict=False)
        pr = PdfFileReader(f_in, strict=False)
        pw.appendPagesFromReader(pr)
        pw._root_object.update(
            {NameObject("/AcroForm"): pr.trailer["/Root"]["/AcroForm"]})
        pw._root_object["/AcroForm"].update(
            {NameObject("/NeedAppearances"): BooleanObject(True)})
        for p in range(pr.getNumPages()):
            self._update_page_form_checkbox_values(pw.getPage(p), {
                fk: fv['/V']
                for fk, fv in fields.items() if '/V' in fv.keys()
            })  # sometimes '/V' disappears from the keys
        self._update_page_form_checkbox_values(pw.getPage(0),
                                               {'points': str(points)})
        f = codecs.open(f_out, 'wb')
        pw.write(f)
        f.close()

        a = PdfAnnotator(f_out)
        for p in range(pr.getNumPages()):
            for dk, dv in dest.items():
                if pr.getDestinationPageNumber(dv) == p and dk.startswith(
                        'ht_'):
                    inds = [int(ind) for ind in dk[3:].split(':')]
                    #                     if inds[2] in solution[inds[1]][1]:
                    if inds[4] in solution[inds[1]][1]:
                        # using some hard-coded values:
                        a.add_annotation(
                            'square',
                            Location(x1=float(dv['/Left']),
                                     y1=float(dv['/Top']),
                                     x2=float(dv['/Left']) + 5,
                                     y2=float(dv['/Top']) + 5,
                                     page=p),
                            Appearance(stroke_color=(0, 1, 0), stroke_width=5),
                        )
        a.write(f_out)
コード例 #18
0
def setup_reader(file: str) -> PdfFileReader:
    reader = PdfFileReader(open(file, "rb"), strict=False)
    if "/AcroForm" in reader.trailer["/Root"]:
        reader.trailer["/Root"]["/AcroForm"].update(
            {NameObject("/NeedAppearances"): BooleanObject(True)})
    return reader
コード例 #19
0
def generate_student_report(a, b):
    def student_data(a, b):
        global dbhost, dbuser, dbpas
        with pymysql.connect(dbhost, dbuser, dbpas, 'exam') as db:
            db.execute(f"SELECT * FROM {b} WHERE name = '{a}'")
            res = db.fetchone()
        return res

    def set_need_appearances_writer(writer):
        try:
            catalog = writer._root_object
            if "/AcroForm" not in catalog:
                writer._root_object.update({
                    NameObject("/AcroForm"):
                    IndirectObject(len(writer._objects), 0, writer)
                })

            need_appearances = NameObject("/NeedAppearances")
            writer._root_object["/AcroForm"][need_appearances] = BooleanObject(
                True)
            return writer

        except Exception as e:
            print('set_need_appearances_writer() catch : ', repr(e))
            return writer

    def create_dict(a):  # Check totals
        data_dict['name'] = a[1]
        data_dict['class'] = get_class_student(a[1])
        data_dict['exam'] = rev_get_exam(b)
        data_dict['english_obt'] = a[2]
        data_dict['english_total'] = a[3]
        data_dict['english_percent'] = str((int(a[2]) / int(a[3])) * 100)[:4]
        data_dict['english_api'] = getapi(data_dict['english_percent'])
        data_dict['science_obt'] = a[4]
        data_dict['science_total'] = a[5]
        data_dict['science_percent'] = str((int(a[4]) / int(a[5])) * 100)[:4]
        data_dict['science_api'] = getapi(data_dict['science_percent'])
        data_dict['math_obt'] = a[6]
        data_dict['math_total'] = a[7]
        data_dict['math_percent'] = str((int(a[6]) / int(a[7])) * 100)[:4]
        data_dict['math_api'] = getapi(data_dict['math_percent'])
        data_dict['social_obt'] = a[8]
        data_dict['social_total'] = a[9]
        data_dict['social_percent'] = str((int(a[8]) / int(a[9])) * 100)[:4]
        data_dict['social_api'] = getapi(data_dict['social_percent'])
        data_dict['obt_total'] = a[-3]
        data_dict['total_total'] = a[-2]
        data_dict['percentage'] = a[-1]
        data_dict['total_api'] = data_dict['english_api'] + data_dict['science_api'] + \
                                 data_dict['math_api'] + data_dict['social_api']
        return data_dict

    x = student_data(a, b)
    data_dict = {}
    outfile = f'{cwd}/uploads/{a}.pdf'
    infile = f'{cwd}/templates/report2.pdf'
    data = create_dict(x)
    input_stream = open(infile, "rb")
    pdf_reader = PyPDF2.PdfFileReader(input_stream, strict=False)
    if "/AcroForm" in pdf_reader.trailer["/Root"]:
        pdf_reader.trailer["/Root"]["/AcroForm"].update(
            {NameObject("/NeedAppearances"): BooleanObject(True)})

    pdf_writer = PyPDF2.PdfFileWriter()
    set_need_appearances_writer(pdf_writer)
    if "/AcroForm" in pdf_writer._root_object:
        pdf_writer._root_object["/AcroForm"].update(
            {NameObject("/NeedAppearances"): BooleanObject(True)})

    pdf_writer.addPage(pdf_reader.getPage(0))
    pdf_writer.updatePageFormFieldValues(pdf_writer.getPage(0), data)
    page = pdf_writer.getPage(0)
    for j in range(0, len(page['/Annots'])):
        writer_annot = page['/Annots'][j].getObject()
        for field in data_dict:
            if writer_annot.get('/T') == field:
                writer_annot.update({
                    NameObject("/Ff"): NumberObject(1)  # make ReadOnly
                })
    output_stream = open(outfile, "wb")
    pdf_writer.write(output_stream)
    input_stream.close()
    output_stream.close()
    outfile = outfile.split('/')[-1]
    return outfile
コード例 #20
0
def write_form(lecturer, employee_dict, radio_dict, choice_dict):

    output = PdfFileWriter()
    if lecturer.job_code[0] == 1630 or lecturer.job_code[0] == 1632:
        template = PdfFileReader(open("Pre6_Data_Summary__Redacted.pdf", 'rb'))
        filename = lecturer.last_name + "." + lecturer.first_name + "_form.pdf"
    else:
        template = PdfFileReader(
            open("CL_Data_Summary_form_Redacted.pdf", 'rb'))
        filename = lecturer.last_name + "." + lecturer.first_name + "_Cont_form.pdf"
    output.cloneReaderDocumentRoot(template)
    output._root_object["/AcroForm"][NameObject(
        "/NeedAppearances")] = BooleanObject(True)

    for i in [0, 1]:

        output.updatePageFormFieldValues(template.getPage(i), employee_dict)

        page = template.getPage(i)

        #Checkboxes and drop downs:From PyPDF Library for updatePageFormFieldValues but edited for NameObject as value
        for j in range(0, len(page['/Annots'])):
            writer_annot = page['/Annots'][j].getObject()

            #dropdowns:changes "I" to index of option chosen ex: second option on list is "1"
            #"V" is the text of the field. Both V and I must be updated
            for field in choice_dict:
                #  print(lecturer.last_name, field)
                if writer_annot.get("/T") == field:

                    writer_annot.update({
                        NameObject("/I"):
                        NameObject(choice_dict[field][0]),
                        NameObject("/V"):
                        TextStringObject(choice_dict[field][1])
                    })

            #checkboxes on pre6 form are kids of a parent object.
            #accesses parent of object to get NameID
            #checkboxes on cont form are accesible by "/T" alone
            for field in radio_dict:
                if "/Parent" in writer_annot:
                    if writer_annot["/Parent"].get("/T") == field:

                        writer_annot.update({
                            NameObject("/V"):
                            NameObject(radio_dict[field]),
                            NameObject("/AS"):
                            NameObject(radio_dict[field])
                        })
                elif writer_annot.get("/T") == field:
                    writer_annot.update({
                        NameObject("/V"):
                        NameObject(radio_dict[field]),
                        NameObject("/AS"):
                        NameObject(radio_dict[field])
                    })
        if i == 0:
            # if there are two start dates and it's the first page add second set of dates to the proposed dates
            if len(lecturer.start) == 2 and (lecturer.break_service == True):
                start_end_2 = lecturer.start[1] + "-" + lecturer.end[1]
                add_comment(output, page, start_end_2,
                            [379.051, 405.913, 536.515, 424.313])
            #if they are eligible for a raise in the middle of the year add a line for a second monthly/annual(pg1 and pg2)
            if len(lecturer.annual) == 2:
                add_comment(output, page,
                            lecturer.start[1] + ": " + lecturer.annual[1],
                            [457.783, 465.165, 582.78, 483.565])
        if i == 1:
            if len(lecturer.monthly) == 2:
                add_comment(output, page,
                            lecturer.start[1] + ": " + lecturer.monthly[1],
                            [440.738, 679.446, 548.738, 697.846])

    outputStream = open(filename, "wb")
    output.write(outputStream)
コード例 #21
0
ファイル: allcamps.py プロジェクト: xc443/all-camps
    def pdffill(self):
        x = self.start_server()
        mapping = self.dic()
        myfile = PdfFileReader("./routes/up/blank_table.pdf")
        writer = PdfFileWriter()
        writer, myfile = self.set_need_appearances_writer(myfile, writer)
        if "/AcroForm" in writer._root_object:
            writer._root_object["/AcroForm"].update(
                {NameObject("/NeedAppearances"): BooleanObject(True)})
        print(1)
        fp = open("./routes/up/blank_table.pdf", 'rb')
        #        pdf_writer = PyPDF2.PdfFileWriter()
        parser = PDFParser(fp)
        doc = PDFDocument(parser)
        fields = resolve1(doc.catalog['AcroForm'])['Fields']

        first_page = myfile.getPage(self.page)
        #for i in fields:
        #    field = resolve1(i)
        #    name, value = field.get('T'), field.get('V')
        ##    print (str(name))
        #    if str(name) == "b'Text11'":
        #        writer.updatePageFormFieldValues(first_page, fields={'Text11':x['firstname']})
        #    if str(name) == "b'Text13'":
        #        writer.updatePageFormFieldValues(first_page, fields={'Text13':x['lastname']})
        #    if str(name) == "b'Text16'":
        #        writer.updatePageFormFieldValues(first_page, fields={'Text16':x['homeaddress']})
        #    if str(name) == "b'Text15'":
        #        writer.updatePageFormFieldValues(first_page, fields={'Text15':x['gender']})
        #    if str(name) == "b'Text14'":
        #        writer.updatePageFormFieldValues(first_page, fields={'Text14':str(x['birthdate'])[:10]})
        for p in x.keys():

            for i in fields:
                temp = []
                field = resolve1(i)
                name, value = field.get('T'), field.get('V')
                label = (re.split(b'\t|\x90s', name))
                q = ""
                for j in label:
                    # temp.append(j.decode('utf-8').lower())
                    q = q + (j.decode('utf-8').lower())
                temp.append(q)
                # print(temp)
                # print(1)
                if (str(name) in mapping.keys()
                        and p in mapping[str(name)]) or p in temp:
                    # print(p)
                    # print(str(name) in mapping.keys() and p in mapping[str(name)])
                    # print( p in temp)

                    if p == "birthdate":
                        writer.updatePageFormFieldValues(
                            first_page,
                            fields={
                                str(name)[2:len(str(name)) - 1]: str(x[p])[:10]
                            })
                    else:
                        print(str(name)[2:len(str(name)) - 1])
                        print(str(x[p]))
                        writer.updatePageFormFieldValues(
                            first_page,
                            fields={
                                str(name)[2:len(str(name)) - 1]: str(x[p])
                            })
        #    print ('{0}: {1}'.format(name, value))
        # writer.addPage(first_page)
        writer.updatePageFormFieldValues(first_page,
                                         fields={'parent1name': "123"})
        return first_page
コード例 #22
0
    def handle(self, *args, **options):
        def set_need_appearances_writer(writer):
            # See 12.7.2 and 7.7.2 for more information:
            # http://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/PDF32000_2008.pdf
            try:
                catalog = writer._root_object
                # get the AcroForm tree and add "/NeedAppearances attribute
                if "/AcroForm" not in catalog:
                    writer._root_object.update({
                        NameObject("/AcroForm"):
                        IndirectObject(len(writer._objects), 0, writer)
                    })

                need_appearances = NameObject("/NeedAppearances")
                writer._root_object["/AcroForm"][
                    need_appearances] = BooleanObject(True)
                return writer

            except Exception as e:
                print('set_need_appearances_writer() catch : ', repr(e))
                return writer

        def calculate_age(age):
            today = date.today()
            return today.year - age.year - ((today.month, today.day) <
                                            (age.month, age.day))

        infile = file_path = os.path.join(settings.PROJECT_ROOT,
                                          'entrega2020.pdf')
        inputStream = open(infile, "rb")
        pdf_reader = PdfFileReader(inputStream, strict=False)
        if "/AcroForm" in pdf_reader.trailer["/Root"]:
            pdf_reader.trailer["/Root"]["/AcroForm"].update(
                {NameObject("/NeedAppearances"): BooleanObject(True)})

        pdf_writer = PdfFileWriter()
        set_need_appearances_writer(pdf_writer)
        if "/AcroForm" in pdf_writer._root_object:
            pdf_writer._root_object["/AcroForm"].update(
                {NameObject("/NeedAppearances"): BooleanObject(True)})

        # personas = Persona.objects.exclude(covid=True).exclude(active=False)
        personas = Persona.objects.filter(active=True).exclude(covid=True)
        # print([ p.nombre_apellido for p in personas])
        # print(personas.count())
        pdf_writer.addPage(pdf_reader.getPage(0))
        for persona in personas:
            if persona.active:
                print(persona.id)
                familiares = persona.hijo.all()
                familiares_gr = persona.hijo.filter(edad__gt=3)
                # print(familiares_pq.count())
                mayores = 0
                menores = 0
                for f in familiares:
                    if calculate_age(f.fecha_nacimiento) > 3:
                        mayores += 1
                    else:
                        menores += 1

                print(mayores)
                print(menores)
                field_dictionary = {
                    "NombreOAR": "ADRA TORREJON",
                    "DireccioOAR": "C/ Primavera 15",
                    "Nombre y apellidos del representante de la unidad familiar":
                    f"{persona.nombre_apellido}",
                    "DNINIEPasaporte 1": f"{persona.dni}",
                    "Teléfono": f"{persona.telefono}",
                    "Domicilio": f"{persona.domicilio}",
                    "Localidad": f"{persona.ciudad}",
                    "CP": "28850",
                    "TOTAL MIEMBROS UNIDAD FAMILIAR":
                    f"{mayores + menores + 1}",
                    "Niños 02 ambos inclusive": f"{menores}",
                    "numarAdra": f"{persona.numero_adra}"
                }

                pdf_writer.updatePageFormFieldValues(pdf_writer.getPage(0),
                                                     field_dictionary)

                # outputStream = open(outfile, "wb")
                # pdf_writer.write(outputStream)

                # outputStream.close()
                # pdf_writer.encrypt(str.lower(f"{persona.numero_adra}"))
                with open(f"./entregas/{persona.numero_adra}.pdf",
                          "wb") as out_file:
                    pdf_writer.write(out_file)
コード例 #23
0
    def generate_separate_lipe_file(self, count, quadro_vp_id):
        pdf_module_path = get_module_resource(
            'l10n_it_account', 'data', 'moduli_pdf',
            'modulo_liquidazione_periodica_iva_editabile.pdf')
        input_stream = open(pdf_module_path, "rb")
        pdf_reader = PyPDF2.PdfFileReader(input_stream, strict=False)

        if "/AcroForm" in pdf_reader.trailer["/Root"]:
            pdf_reader.trailer["/Root"]["/AcroForm"].update(
                {NameObject("/NeedAppearances"): BooleanObject(True)})

        pdf_writer = PyPDF2.PdfFileWriter()
        self.set_need_appearances_writer(pdf_writer)

        if "/AcroForm" in pdf_writer._root_object:
            # Acro form is form field, set needs appearances to fix printing issues
            pdf_writer._root_object["/AcroForm"].update(
                {NameObject("/NeedAppearances"): BooleanObject(True)})

        data_dict_pag2 = {
            'CODICE FISCALE_2' + str(count):
            self.taxpayer_fiscalcode,
            'MODULO_N' + str(count):
            str(count).zfill(2),
            'MESE' + str(count):
            str(quadro_vp_id.month).zfill(2)
            if quadro_vp_id.period_type == 'month' else '',
            'TRIMESTRE' + str(count):
            str(quadro_vp_id.quarter).zfill(2)
            if quadro_vp_id.period_type == 'quarter' else '',
            'SUBFORNITURE' + str(count):
            quadro_vp_id.subcontracting,
            'EVENTI_ECCEZIONALI' + str(count):
            quadro_vp_id.exceptional_events,
            'OPERAZIONI_STRAORDINARIE' + str(count):
            '',
            'VP2' + str(count):
            str(quadro_vp_id.imponibile_operazioni_attive).replace('.', ' '),
            'VP3' + str(count):
            str(quadro_vp_id.imponibile_operazioni_passive).replace('.', ' '),
            'VP4' + str(count):
            str(quadro_vp_id.iva_esigibile).replace('.', ' '),
            'VP5' + str(count):
            str(quadro_vp_id.iva_detratta).replace('.', ' '),
            'VP6_D' + str(count):
            str(quadro_vp_id.iva_dovuta_debito).replace('.', ' '),
            'VP6_C' + str(count):
            str(quadro_vp_id.iva_dovuta_credito).replace('.', ' '),
            'VP7' + str(count):
            str(quadro_vp_id.debito_periodo_precedente).replace('.', ' '),
            'VP8' + str(count):
            str(quadro_vp_id.credito_periodo_precedente).replace('.', ' '),
            'VP9' + str(count):
            str(quadro_vp_id.credito_anno_precedente).replace('.', ' '),
            'VP10' + str(count):
            str(quadro_vp_id.versamento_auto_UE).replace('.', ' '),
            'VP11' + str(count):
            str(quadro_vp_id.crediti_imposta).replace('.', ' '),
            'VP12' + str(count):
            str(quadro_vp_id.interessi_dovuti).replace('.', ' '),
            'VP13' + str(count):
            str(quadro_vp_id.accounto_dovuto).replace('.', ' '),
            'VP14_D' + str(count):
            str(quadro_vp_id.iva_da_versare).replace('.', ' '),
            'VP14_C' + str(count):
            str(quadro_vp_id.iva_a_credito).replace('.', ' '),
            'ACCONTO_DOVUTO' + str(count):
            ''
        }

        page = pdf_reader.getPage(2)
        pdf_writer.addPage(page)
        renamed_page_field = pdf_writer.getPage(0)
        self.pdf_suffix_fields(renamed_page_field, str(count))
        pdf_writer.updatePageFormFieldValues(renamed_page_field,
                                             data_dict_pag2)

        output_stream = BytesIO()
        pdf_writer.write(output_stream)
        return output_stream.getvalue()
コード例 #24
0
ファイル: routes.py プロジェクト: gwright99/pcoi
def create_PDF():
	''' This was really hard to figure out.
	Look at: https://github.com/mstamy2/PyPDF2/issues/355 (Tromar44, Jan 25 2019) 
	entry for details on setup.
	'''
	js_args = request.args.get('args')
	js_args = base64.b64decode(js_args)
	js_args = json.loads(js_args)
	print('js_args are: ', js_args)
	trx_details = js_args['trx_details']
	print('trx_details are: ', trx_details)
	print('trx_details type is: ', type(trx_details))
	trx_details = ast.literal_eval(trx_details)
	print('trx_details type is: ', type(trx_details))

	
	# This is kludged. "pdf_folder" defined in app.__init__
	# Other articles are more elegant in discovering. I've hardcoded.
	input_path = os.path.join(app.pdf_folder, 'scanned_dhdr_w_ids.pdf')
	output_path = os.path.join(app.pdf_folder, 'scanned_dhdr_w_ids_autopopulated.pdf')
	
	# Load field_dictionary with arg values. Then cleanse those fields that contain 
	# the word "undefined"
	
	field_dictionary = {
		'hcp_Health_Number': trx_details['patient_hcn'],
		'hcp_Patient_Name': '{}; {}'.format(trx_details['patient_family_name'], 
											trx_details['patient_given_names']),
		'hcp_Facility': '{} - {}'.format(trx_details['org_upi'],
											trx_details['org_name']),
		'hcp_Consent_Obtained_By': '{}; {}'.format(trx_details['provider_family_name'],
													trx_details['provider_given_names']),
		'hcp_SDM_Type': js_args['sdm_code'],
		'patient_Name_Of_HCP': '{}; {}'.format(trx_details['provider_family_name'],
													trx_details['provider_given_names']),
	}
	
	for k,v in js_args.items():
		if 'undefined' in js_args[k]:
			js_args[k] = ''
	
	# Set hcp_Consent_Provided_By field (Patient vs SDM)
	if (js_args['override_type'] == 'ECSDM'):
		print('SDM values found')
		field_dictionary['hcp_Consent_Provided_By_SDM'] = 'X'
		field_dictionary['patient_Name_Of_SDM'] = '{}; {}'.format(js_args['sdm_family_name'], 
											js_args['sdm_given_names'])	
	else:
		field_dictionary['hcp_Consent_Provided_By_Patient'] = 'X'
		field_dictionary['patient_Name_Of_SDM'] = field_dictionary['hcp_Patient_Name']
		
	# Set the date and time form was generated
	date = datetime.datetime.now()
	field_dictionary['hcp_Date'] = '{}-{}-{}'.format(date.year, date.month, date.day)
	field_dictionary['hcp_time'] = '{}:{}:{}'.format(date.hour, date.minute, date.second)
	field_dictionary['patient_Date'] = '{}-{}-{}'.format(date.year, date.month, date.day)

	#------------ Create PDF logic -----------
	infile = input_path
	outfile = output_path
	
	def set_need_appearances_writer(writer: PdfFileWriter):
		# See 12.7.2 and 7.7.2 for more information: http://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/PDF32000_2008.pdf
		try:
			catalog = writer._root_object
			# get the AcroForm tree
			if "/AcroForm" not in catalog:
				writer._root_object.update({
					NameObject("/AcroForm"): IndirectObject(len(writer._objects), 0, writer)})

			need_appearances = NameObject("/NeedAppearances")
			writer._root_object["/AcroForm"][need_appearances] = BooleanObject(True)
			return writer
		except Exception as e:
			print('set_need_appearances_writer() catch : ', repr(e))
			return writer

	# Uncomment if PDF generation breaks & re-indent ifs below
	#with open(infile, 'rb') as f:
	#	pdf = PdfFileReader(f)
	
	pdf = PdfFileReader(open(infile, "rb"), strict=False)	
	if "/AcroForm" in pdf.trailer["/Root"]:
		pdf.trailer["/Root"]["/AcroForm"].update(
			{NameObject("/NeedAppearances"): BooleanObject(True)})

	pdf2 = PdfFileWriter()
	set_need_appearances_writer(pdf2)
	if "/AcroForm" in pdf2._root_object:
		pdf2._root_object["/AcroForm"].update(
			{NameObject("/NeedAppearances"): BooleanObject(True)})

	pdf2.addPage(pdf.getPage(0))
	pdf2.updatePageFormFieldValues(pdf2.getPage(0), field_dictionary)

	# See https://www.blog.pythonlibrary.org/2013/07/16/pypdf-how-to-write-a-pdf-to-memory/
	# for writing PDF to memory
	
	# This successfully writes a PDF to file
	outputStream = open(outfile, "wb")
	pdf2.write(outputStream)
		
	
	# THIS RETURNS pdf with values!!!!
	# ALWAYS DELETE BROWSER CACHE - this was only returning text before
	# https://www.reddit.com/r/learnpython/comments/4b456s/using_flask_to_return_pdfs_how_do_i_do_it/
	# https://stackoverflow.com/questions/41731457/flask-force-download-pdf-files-to-open-in-browser
	# https://gist.github.com/widoyo/3897853
	# https://stackoverflow.com/questions/18281433/flask-handling-a-pdf-as-its-own-page
	tmp = BytesIO()
	pdf2.write(tmp)
	resp = make_response(tmp.getvalue(), 200)
	resp.headers['Content-Disposition'] = "inline; filename=%s" % 'populated_pdf.pdf'
	resp.mimetype = "application/pdf"
	return resp
	
	'''
	# This returns text in PDF only too
	# https://gist.github.com/Miserlou/fcf0e9410364d98a853cb7ff42efd35a
	with open(outfile, "rb") as pdf_to_send:
		return send_file(
			BytesIO(pdf_to_send.read()),
			attachment_filename='popped_pdf.pdf',
			mimetype="application/pdf"
		)'''
	
	'''
コード例 #25
0
    def get_export_pdf(self):
        """
        Funzione che compila il modulo standard della comunicazione periodica
        IVA dell'AdE, il modulo è presente nella cartella data/moduli_pdf
        """
        pdfs_list = []

        pdf_module_path = get_module_resource(
            'l10n_it_account', 'data', 'moduli_pdf',
            'modulo_liquidazione_periodica_iva_editabile.pdf')
        input_stream = open(pdf_module_path, "rb")

        pdf_reader = PyPDF2.PdfFileReader(input_stream, strict=False)

        if "/AcroForm" in pdf_reader.trailer["/Root"]:
            pdf_reader.trailer["/Root"]["/AcroForm"].update(
                {NameObject("/NeedAppearances"): BooleanObject(True)})

        pdf_writer = PyPDF2.PdfFileWriter()

        self.set_need_appearances_writer(pdf_writer)
        if "/AcroForm" in pdf_writer._root_object:
            # Acro form is form field, set needs appearances to fix printing issues
            pdf_writer._root_object["/AcroForm"].update(
                {NameObject("/NeedAppearances"): BooleanObject(True)})

        data_dict_pag1 = {
            'CODICE_FISCALE':
            self.taxpayer_fiscalcode,
            'ANNO_IMPOSTA':
            self.year,
            'CODICE_CARICA':
            self.codice_carica_id.code,
            'PARTITA_IVA':
            self.taxpayer_vat,
            'PARTITA_IVA_CONTROLLANTE':
            self.controller_vat if self.controller_vat else '',
            'ULTIMO_MESE':
            self.last_month,
            'LIQUIDAZIONE_GRUPPO':
            '',
            'CODICE_FISCALE_DICHIARANTE':
            self.declarant_fiscalcode if self.declarant_fiscalcode else '',
            'CODICE_FISCALE_SOCIETA_DICHIARANTE':
            '',
            'FIRMA':
            'X' if self.declarant_sign else '',
            'CODICE_FISCALE_INCARICATO':
            self.delegate_fiscalcode if self.delegate_fiscalcode else '',
            'IMPEGNO_PRESENTAZIONE':
            '',
            'IMPEGNO_GIORNO_MESE_ANNO':
            self.date_commitment if self.date_commitment else '',
            'FIRMA_INCARICATO':
            'X' if self.delegate_sign else '',
        }

        pdf_writer.addPage(pdf_reader.getPage(0))
        pdf_writer.addPage(pdf_reader.getPage(1))
        page = pdf_writer.getPage(1)
        pdf_writer.updatePageFormFieldValues(page, data_dict_pag1)

        count = 0  #Contatore Modulo

        for quadro_vp_id in self.quadri_vp_ids:
            count += 1
            pdfs_list.append(
                self.generate_separate_lipe_file(count, quadro_vp_id))

        output_stream = BytesIO()
        pdf_writer.write(output_stream)
        pdfs_list.append(output_stream.getvalue())
        return pdfs_list
コード例 #26
0
def generar_hoja_entrega(request, pk):
    """
    Generador de hoja de entrega para cada beneficiario en parte
    :param request:
    :param pk: id persona
    :return: pdf generado
    """
    # infile = file_path = os.path.join(settings.PROJECT_ROOT, 'entrega2020.pdf')
    infile = os.path.join(os.path.abspath('source_files'), '2021_entrega.pdf')
    inputStream = open(infile, "rb")
    pdf_reader = PdfFileReader(inputStream, strict=False)
    if "/AcroForm" in pdf_reader.trailer["/Root"]:
        pdf_reader.trailer["/Root"]["/AcroForm"].update(
            {NameObject("/NeedAppearances"): BooleanObject(True)})

    pdf_writer = PdfFileWriter()
    set_need_appearances_writer(pdf_writer)
    if "/AcroForm" in pdf_writer._root_object:
        pdf_writer._root_object["/AcroForm"].update(
            {NameObject("/NeedAppearances"): BooleanObject(True)})

    persona = Persona.objects.get(id=pk)
    familiares = persona.hijo.all()

    mayores = 0
    menores = 0
    for f in familiares:
        if calculate_age(f.fecha_nacimiento) > 3:
            mayores += 1
        else:
            menores += 1

    field_dictionary = {
        "NombreOAR": "ADRA TORREJON",
        "DireccioOAR": "C/ Primavera 15",
        "Nombre y apellidos del representante de la unidad familiar":
        f"{persona.nombre_apellido}",
        "DNINIEPasaporte 1": f"{persona.dni}",
        "Teléfono": f"{persona.telefono}",
        "Domicilio": f"{persona.domicilio}",
        "Localidad": f"{persona.ciudad}",
        "CP": "28850",
        "TOTAL MIEMBROS UNIDAD FAMILIAR": f"{mayores + menores + 1}",
        "Niños 02 ambos inclusive": f"{menores}",
        "numarAdra": f"{persona.numero_adra}"
    }

    pdf_writer.addPage(pdf_reader.getPage(0))
    pdf_writer.updatePageFormFieldValues(pdf_writer.getPage(0),
                                         field_dictionary)

    # outputStream = open(outfile, "wb")
    # pdf_writer.write(outputStream)

    # outputStream.close()

    # extractedPage = open(pdf_file_path, 'rb')
    response = HttpResponse(content_type='application/pdf')
    response[
        'Content-Disposition'] = f'attachment;filename="{persona.numero_adra}.pdf"'
    pdf_writer.write(response)
    inputStream.close()
    return response
コード例 #27
0
 def _set_appearances_to_reader(self, reader: PdfFileReader) -> None:
     if "/AcroForm" in reader.trailer["/Root"]:
         reader.trailer["/Root"]["/AcroForm"].update({NameObject("/NeedAppearances"): BooleanObject(True)})