简体   繁体   中英

matplotlib setting pdf raster resolution using pdfpages savefig dpi

I have a project that generates a set of charts using matplotlib and exports each one as an individual PNG file. The client also wants the group of charts output as a single PDF file. We have successfully got this to work using PIL Image and matplotlib PdfPages to import each PNG on a separate page and export the multi-page PDF, but the PDF output quality is unacceptable. If I use anything other than dpi=100 with savefig, then output is blank. Any suggestions on how to export a PDF with higher raster resolution?

  pp = PdfPages(filepath+'Treatment Zone Charts.pdf')

  for file in os.listdir(filepath):
      if "Treatment Zone Charts" in file and file.endswith(".png"):
          print filepath+file

          #read PNG image
          im = Image.open(filepath+'/'+file)
          im = im.resize((1100,850),Image.ANTIALIAS)

          im = np.array(im).astype(np.float) / 255

          # Create a figure with size w,h tuple in inches
          fig = Figure(figsize=(11,8.5))
          # Create a canvas and add the figure to it.
          canvas = PDF_FigureCanvas(fig)

          #add image to plot
          fig.figimage(im, 0, -220, zorder = 1)

          # Save the Plot to the PDF file
          pp.savefig(fig, dpi=100)

  #close the PDF file after the last plot is created
  pp.close()

The output was blank because the image was positioned off of the canvas. For dpi=200 and no resizing of the original image, we needed to modify figimage to:

          fig.figimage(im, 0, -1080, zorder = 1)

The output is very sensitive to the y-value, a small change from -1080 and the image was placed off the top or bottom of the page. I don't understand why the dpi setting has this effect on the figimage y parameter, but this now produces PDF output with good quality.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM