Skip to content

Instantly share code, notes, and snippets.

@dov
Created January 15, 2021 08:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dov/a2f3afb3ea652c6f11d9dd69d304e9ee to your computer and use it in GitHub Desktop.
Save dov/a2f3afb3ea652c6f11d9dd69d304e9ee to your computer and use it in GitHub Desktop.
A script for converting a list of svg files to a pdf files via inkscape and png
#!/usr/bin/python
######################################################################
# A script for translating a list of svg (pages) to a pdf file
# via inkscape and cairo.
#
# The reason I used png steps as an intermediate is two fold:
#
# 1. It makes the pdf files less editable (which might be good
# when sending documents)
# 2. There is a bug in the pdf output and some elements are not
# output
#
# This script is licensed under the LGPLv2.0
#
# 2021-01-15 Fri
# Dov Grobgeld <dov.grobgeld@gmail.com>
######################################################################
import os,sys
import cairo
import argparse
# Translate mm to svg. Corresponding to 90dpi. The default(?) resolution for svg.
svg2mm = 0.2822222
mm2svg = 1.0/svg2mm
def draw_image(ctx, image, left_top, width_height):
"""Draw a scaled image on the given cairo context."""
# unpack
left,top = left_top
width,height = width_height
image_surface = cairo.ImageSurface.create_from_png(image)
# calculate proportional scaling
img_height = image_surface.get_height()
img_width = image_surface.get_width()
width_ratio = float(width) / float(img_width)
height_ratio = float(height) / float(img_height)
scale_xy = min(height_ratio, width_ratio)
# scale image and add it
ctx.save()
ctx.scale(scale_xy, scale_xy)
ctx.translate(left, top)
ctx.set_source_surface(image_surface)
ctx.paint()
ctx.restore()
# Defaults
parser = argparse.ArgumentParser(description='Translate svg files to pdf via png files and inkscape')
parser.add_argument('files',
nargs='+',
help='svg filenames')
parser.add_argument('-o','--output',
type=str,
dest='output',
default='out.pdf',
help='output filename')
args = parser.parse_args()
files = args.files
output_filename=args.output
width, height = 210*mm2svg,297*mm2svg
surface = cairo.PDFSurface (output_filename, width, height)
ctx = cairo.Context (surface)
for i,fn in enumerate(files):
export_fn = f'/tmp/p{i:02d}.png'
cmd = f'inkscape -w 2500 --export-filename={export_fn} --export-type="png" {fn}'
os.system(cmd)
image_filename = export_fn
draw_image(ctx, image_filename, (0,0), (width,height))
ctx.show_page()
surface.finish()
print(f'Done writing to {output_filename}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment