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! Show
does not do what you think it does. As soon as you convert
Then the That is your first error.
Yes, you must supply a string to The second is assuming
You can use Working code: 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 += ( ' 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.. |