Python save output to pdf

You are doing everything correct to write output into a PDF. But you are not getting the result you "want" because your Python code is not correct!

for i in str(data):
      .. do stuff with i here ..

does not do what you think it does. As soon as you convert data to a string, per str(data), it magically becomes the string

[1, 2, 3, 4, 5, 6]

Then the for loop iterates over the contents of that string – its characters – and writes them one by one to the PDF.

That is your first error. Yes, you must supply a string to pdf.write – but only of each separate item you want to write, not the entire input object.

The second is assuming pdf.write outputs a line including a return at the end. It does not:

This method prints text from the current position. When the right margin is reached (or the \n character is met), a line break occurs and text continues from the left margin. Upon method exit, the current position is left just at the end of the text.
(https://pyfpdf.readthedocs.io/en/latest/reference/write/index.html)

You can use ln to insert line breaks, or append \n at the end of each string just before writing it.

Working code:

import fpdf

data=[1,2,3,4,5,6]

pdf = fpdf.FPDF(format='letter')
pdf.add_page()
pdf.set_font("Arial", size=12)

for i in data:
    pdf.write(5,str(i))
    pdf.ln()
pdf.output("testings.pdf")

23 Python code examples are found related to " save pdf". You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

Example 1

def save_as_pdf(png_path):
    assert png_path.endswith('.png')
    pdf_path = re.sub('.png$', '.pdf', png_path)
    print "Writing: %s"%pdf_path
    plotter.plt.savefig(pdf_path)
    return 

Example 2

def save_as_pdf(self, results, url):
        tmpdir = mkdtemp()

        try:
            options = {"load-error-handling": "ignore"}

            pdfkit.from_url(url, path.join(tmpdir, 'out.pdf'), options=options)

            with open(path.join(tmpdir, 'out.pdf'), 'rb') as pdf:
                pdf_import = AttachedFile.from_content(
                    pdf, 'import.pdf', 'application/pdf')

            results.investigation.update(import_document=pdf_import)
        except Exception as e:
            print(e)

        rmtree(tmpdir) 

Example 3

def save_pdf(full_dir,filename,i):
  if not os.path.exists(full_dir):
    os.makedirs(full_dir)
  # Open the URL and retrieve data
  file_loc = full_dir + filename
  if not os.path.exists(file_loc) or force == True:
    if i.startswith("//"):
      i = "http:" + i
    print "Downloading : " + i  
    web = urllib.urlopen(i)
    print "Saving to : " + file_loc
    # Save Data to disk
    output = open(file_loc,'wb')
    output.write(web.read())
    output.close()
  else:
    print "Skipping " + i + " - file exists or is a dated API document, use './getAWSdocs.py --force' to force override" 

Example 4

def save_pdf_binary_string(
        self, pdf_string: bytes, out_filename: str
    ) -> pathlib.Path:
        """ Save the binary string to the store using the out_filename

        Parameters
        ----------
        pdf_string : str
            String representing a pdf in binary format

        out_filename: str
            The name of the pdf file that will stored

        Returns
        -------
        None

        """
        pdf_filename = self.store_path.joinpath(out_filename)
        with open(pdf_filename, "wb") as fp:
            fp.write(pdf_string)

        return pdf_filename 

Example 5

def save_pdf(self, response):
		""" Save pdf files """
		path = response.url.split('/')[-1]
		self.logger.info('Saving PDF %s', path);
		with open(path, 'wb') as file:
			file.write(response.body); 

Example 6

def save_pdf(self, file_name='graph.pdf', prog='dot'):
        """Draw the graph and save as an image or pdf file.

        Parameters
        ----------
        file_name : Optional[str]
            The name of the file to save the graph as. Default: graph.pdf
        prog : Optional[str]
            The graphviz program to use for graph layout. Default: dot
        """
        self.graph.draw(file_name, prog=prog) 

Example 7

def save_pdf(self):
        """save the writer to a pdf file with name 'name_new.pdf' """
        if os.path.exists(self._new_path):
            os.remove(self._new_path)
        with open(self._new_path, 'wb') as out:
            self.writer.write(out)
        return self._new_path 

Example 8

def setSavePlotsToPDF(value):
    """ Sets whether plots should be saved to PDF. """
    global __save_plots_to_pdf
    __save_plots_to_pdf = value


##############################################
# Plotting helpers
############################################## 

Example 9

def save_pdf(self, jarvis, pdf_bytes, destination):
        """
        Save the pdf to the thus supplied location
        or prompt the user to choose a new location
        """
        pdf_file = open(destination, 'wb')
        pdf_file.write(pdf_bytes)
        pdf_file.close()
        jarvis.say('Your pdf is created successfully', Fore.GREEN) 

Example 10

def save_as_pdf(self):
        dialog = QtGui.QFileDialog(self)
        dialog.setDefaultSuffix("pdf")
        dialog.setWindowTitle("Save Figure as PDF...")
        dialog.setAcceptMode(QtGui.QFileDialog.AcceptSave)
        dialog.setFileMode(QtGui.QFileDialog.AnyFile)
        dialog.fileSelected.connect(self.save_as_pdf_to_file)
        dialog.exec() 

Example 11

def save_as_pdf(self, output_dir):
        from .utils.img2pdf import image_dir_to_pdf
        chapter_dir = self.save(output_dir)
        pdf_path = self.get_chapter_pdf_path(output_dir)
        image_dir_to_pdf(img_dir=chapter_dir,
                         target_path=pdf_path,
                         sort_by=lambda x: int(x.split('.')[0]))
        return pdf_path 

Example 12

def save_pdf(user, orig_name, pdf_blob):
    """
    Given a User and a PDF file represented as a stream,
    create the UploadedPDF object.

    :returns: the status context telling whether the operation has succeded.
    """

    response = {'status': 'error'}
    # Check that the file is a valid PDF by extracting the first page
    res = make_thumbnail(pdf_blob)
    if res is None:
        response['message'] = _('Invalid PDF file.')
        return response

    num_pages, png_blob = res

    # Otherwise we save the file!
    upload = UploadedPDF(
            user=user,
            num_pages=num_pages,
            orig_name=orig_name[:MAX_ORIG_NAME_LENGTH])
    f = ContentFile(pdf_blob)
    thumbnail_file = ContentFile(png_blob)
    upload.file.save('document.pdf', f)
    upload.thumbnail.save('thumbnail.png', thumbnail_file)
    upload.save()

    response = {
            'status': 'success',
            'size': round(len(pdf_blob) / 1024 / 1024, 2), # Size in MB
            'num_pages': num_pages,
            'thumbnail': upload.thumbnail.url,
            'file_id': upload.id,
            }
    return response 

Example 13

def save_pdf(path):
  """
  Saves a pdf of the current matplotlib figure.

  :param path: str, filepath to save to
  """

  pp = PdfPages(path)
  pp.savefig(pyplot.gcf())
  pp.close() 

Example 14

def get_pdf_save_full_path(path, pdfname):
    """
        path : folder where the pdf shall be saved to
        pdfname : name the pdf should be given
    """
    if path is None or len(path) == 0:
        return None
    c = 0
    if pdfname.lower().endswith(".pdf"):
        pdfname = pdfname[:-4]
    while os.path.isfile(os.path.join(path, pdfname + ".pdf")):
        pdfname += "-" + str(c) 
        c += 1 
    path = os.path.join(path, pdfname + ".pdf")
    return path 

Example 15

def save_pdf(self):
        save_name = QtGui.QFileDialog.getSaveFileName(self, self.tr("Save PDF"), '.', self.tr("Packets Files(*.pdf)"))
        if save_name:
            name = str(save_name + '.pdf')
            SELECT_INFO.pdfdump(name)
            QtGui.QMessageBox.information(self, u"保存成功", self.tr("PDF保存成功!")) 

Example 16

def save_pdf(self, response):
        path = self.get_path(response.url)
        info(path)
        with open(path, "wb") as f:
            f.write(response.body) 

Example 17

def save_as_pdf(self):
        from matplotlib.backends.backend_pdf import PdfPages
        with PdfPages(os.path.join(self.path, self.name+str(".pdf"))) as pdf:
            pdf.savefig()
            plt.close() 

Example 18

def save_as_pdf(s):
    global i
    try:
        client = pdfcrowd.Client("mkap1234", "fc5ada9fbd1c55f46822d6e9e985a9bb")
        output_file = open('amazon'+str(i)+'.pdf', 'wb')
        i=i+1
        html=get_page(s)
        client.convertHtml(html, output_file)
        output_file.close()
    except pdfcrowd.Error,why:
        print 'Failed:', why 

Example 19

def SaveAsPDF(self):
        """ Save Table as pdf
            The drawings are saved by default
        """
        timestamp = _seconds_to_time(self.player.currentInfo)

        # Frame save drawings
        frame = BurnDrawingsImage(self.player.videoWidget.currentFrame(), self.player.videoWidget.grab(self.player.videoWidget.surface.videoRect()).toImage())

        data = self.player.GetPacketData()
        rows = self.VManager.rowCount()
        columns = self.VManager.columnCount()
        fileName = self.player.fileName

        out, _ = askForFiles(self, QCoreApplication.translate(
            "QgsFmvMetadata", "Save PDF"),
            isSave=True,
            exts='pdf')
        if not out:
            return

        task = QgsTask.fromFunction('Save PDF Report Task',
                                    self.CreatePDF,
                                    out=out,
                                    timestamp=timestamp,
                                    data=data,
                                    frame=frame,
                                    rows=rows,
                                    columns=columns,
                                    fileName=fileName,
                                    VManager=self.VManager,
                                    on_finished=self.finishedTask,
                                    flags=QgsTask.CanCancel)

        QgsApplication.taskManager().addTask(task)
        return 

Example 20

def save_pdf(htmls, file_name):

    options = {

        'page-size': 'Letter',

        'margin-top': '0.75in',

        'margin-right': '0.75in',

        'margin-bottom': '0.75in',

        'margin-left': '0.75in',

        'encoding': "UTF-8",

        'custom-header': [

            ('Accept-Encoding', 'gzip')

        ],

        'cookie': [

            ('cookie-name1', 'cookie-value1'),

            ('cookie-name2', 'cookie-value2'),

        ],

        'outline-depth': 10,

    }

    pdfkit.from_file(htmls, file_name, options=options) 

Example 21

def save_pdf(self, pdf, filename):
        pdf_name_formatter = self._conf.get('common', 'filename_prefix_format')

        if not self._conf.getboolean('common', 'overwrite_existing_file'):
            pdf_name_formatter += '_' + str(round(time.time() * 1000000))

        pdf_metadata = self.get_pdf_metadata(pdf)
        query_type = self.guess_query_type(self._input)

        if query_type in ['doi', 'pmid']:
            pdf_metadata['id'] = self._input
        else:
            for patten in ['_{id}', '{id}_', '{id}']:
                pdf_name_formatter = pdf_name_formatter.replace(patten, '')

        pdf_name_formatter += '_' + filename if pdf_name_formatter else filename

        try:
            pdf_name = pdf_name_formatter.format(**pdf_metadata)
        except Exception as e:
            self.log(self.tr('Unsupported filename keywords: ') + pdf_name_formatter, logging.ERROR)
            return

        pdf_name = self._illegal_filename_pattern.sub('-', pdf_name)
        pdf_path = str(Path(self._conf.get('common', 'save_to_dir')) / pdf_name)

        with open(pdf_path, 'wb') as fp:
            fp.write(pdf)

        pdf_link = '{pdf_path}'.format(pdf_path=pdf_path)

        self.log(self.tr('Saved PDF as: ') + pdf_link, logging.INFO) 

Example 22

def save_articles_as_html_and_pdf():
    print("All links scraped, extracting articles")
    # Formatting the html for articles
    all_articles = (
        ""
        ""
        ''
        ''
        ''
        ""
    )

    all_articles += (
        '

' + category_url.title() + " Archive


" ) all_articles += '

Index


' for x in range(len(articles)): all_articles += ( '' + '

' + str(x + 1) + ".\t\t" + articles[x].title + "


" ) for x in range(len(articles)): all_articles += ( '
' + articles[x].content.decode("utf-8") ) all_articles += """""" html_file_name = "G4G_" + category_url.title() + ".html" html_file = open(html_file_name, "w") html_file.write(all_articles.encode("utf-8")) html_file.close() pdf_file_name = "G4G_" + category_url.title() + ".pdf" print("Generating PDF " + pdf_file_name) html_to_pdf_command = "wkhtmltopdf " + html_file_name + " " + pdf_file_name system(html_to_pdf_command)

Example 23

def save_pdf(self, html):
        chooser = Gtk.FileChooserDialog("Export PDF", None, Gtk.FileChooserAction.SAVE,
                                        (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
                                         Gtk.STOCK_OK, Gtk.ResponseType.OK))
        self.set_file_chooser_path(chooser)
        pdf_filter = Gtk.FileFilter()
        pdf_filter.add_pattern("*.pdf")
        pdf_filter.set_name("PDF Files")
        chooser.add_filter(pdf_filter)
        chooser.set_do_overwrite_confirmation(True)
        response = chooser.run()
        if response == Gtk.ResponseType.OK:
            file_name = chooser.get_filename()
            if not file_name.endswith(".pdf"):
                file_name += ".pdf"
            try:
                pdfkit.from_string(html, file_name, options= {'quiet': '', 'page-size': 'Letter',
                    'margin-top': '0.75in',
                    'margin-right': '0.75in',
                    'margin-bottom': '0.75in',
                    'margin-left': '0.75in',
                    'encoding': "UTF-8",
                    'javascript-delay' : '550',
                    'no-outline': None})
            except:
                try:
                    # Failed so try with no options
                    pdfkit.from_string(html, file_name)
                except:
                    # Pdf Export failed, show warning message
                    if not self.pdf_error_warning:
                        self.pdf_error_warning = True
                        print("\nRemarkable Error:\tPDF Export Failed!!")

                    pdf_fail_dialog = Gtk.MessageDialog(self, 0, Gtk.MessageType.ERROR,
                            Gtk.ButtonsType.CANCEL, "PDF EXPORT FAILED")
                    pdf_fail_dialog.format_secondary_text(
                            "File export to PDF was unsuccessful.")
                    pdf_fail_dialog.run()
                    pdf_fail_dialog.destroy()
        elif response == Gtk.ResponseType.CANCEL:
            pass

        chooser.destroy()
        self.window.set_sensitive(True) 

Can Python produce a PDF?

Fortunately, the Python ecosystem has some great packages for reading, manipulating, and creating PDF files. In this tutorial, you'll learn how to: Read text from a PDF.

How do I save output in Python?

Redirect Print Output to a File in Python.
Use the write() Function to Print Output to a File in Python..
Use the print() Function to Print Output to a File in Python..
Use sys.stdout to Print Output to a File in Python..
Use the contextlib.redirect_stdout() Function to Print Output to a File in Python..

How do I create a Python PDF reader?

Practical Data Science using Python.
Install the requirement by typing. ... .
Import filedialog to create a dialog box for selecting the file from the local directory..
Create a Text Widget and add some Menus to it like Open, Clear, and Quit..
Define a function for each Menu..
Define a function to open the file..

How do I convert code to PDF?

How to convert HTML pages into PDF files:.
On a Windows computer, open an HTML web page in Internet Explorer, Google Chrome, or Firefox. ... .
Click the “Convert to PDF” button in the Adobe PDF toolbar to start the PDF conversion..
Enter a file name and save your new PDF file in a desired location..