问题
I have a series of graphs (.png files) and I want to put four of them into an A4 page and continue doing this for the rest of my graphs. Is it possible to do it with Python?
回答1:
If you're just asking how to tile four images together into a larger image, this is easy to do with most image-processing libraries.
I'll show how to do it using PIL/Pillow:
import sys
from PIL import Image
width, height = int(8.27 * 300), int(11.7 * 300) # A4 at 300dpi
images = sys.argv[1:]
groups = [images[i:i+4] for i in range(0, len(images), 4)]
for i, group in enumerate(groups):
page = Image.new('RGB', (width, height), 'white')
page.paste(Image.open(group[0]), box=(0, 0))
page.paste(Image.open(group[1]), box=(int(width/2.+.5), 0))
page.paste(Image.open(group[2]), box=(0, int(height/2.+.5)))
page.paste(Image.open(group[3]), box=(int(width/2.+.5), int(height/2.+.5)))
page.save('page{}.pdf'.format(i))
This is meant as sample code, not a complete solution to your problem. A few caveats:
- This generates a separate PDF file for each page.
- I placed the PNG files at the upper-left corner of each quadrant of the page. I don't know where you want them placed, but it's probably not exactly that. (Many printers can't print all the way to the margins, and, even if they can, you usually don't want them to.)
- I didn't scale the images, which might be a problem if your graphs are 100x100, or 2000x2000.
- I assumed you wanted to print out at 300dpi.
来源:https://stackoverflow.com/questions/19237253/put-series-of-images-into-one-a4-pages-using-python