Welcome, guest | Sign In | My Account | Store | Cart

Program to convert JPEG to PDF. Technically it just embeds the JPEG in a landscape US letter size PDF page. When you might need it?: When you have to scan a document and do not have scanner handy, you can take a photograph of the document with webcam, and embed the JPEG into PDF - effectively works as a scanner.

Python, 36 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
###############################
## jpg2pdf - Embeds JPEG in PDF
###############################
import sys

from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, flowables

__jpgname = str()
def drawPageFrame(canvas, doc):
    width, height = letter
    canvas.saveState()
    canvas.drawImage(
        __jpgname, 0, 0, height, width,
        preserveAspectRatio=True, anchor='c')
    canvas.restoreState()
    
def jpg2pdf(pdfname):
    width, height = letter

    # To make it landscape, pagesize is reversed
    # You can modify the code to add PDF metadata if you want
    doc = SimpleDocTemplate(pdfname, pagesize=(height, width))
    elem = []

    elem.append(flowables.Macro('canvas.saveState()'))
    elem.append(flowables.Macro('canvas.restoreState()'))

    doc.build(elem, onFirstPage=drawPageFrame)

if __name__ == '__main__':
    if len(sys.argv) < 3:
        print("Usage: python jpg2pdf.py <jpgname> <pdfname>")
        exit(1)
    __jpgname = sys.argv[1]
    jpg2pdf(sys.argv[2])

When you might need it?: When you have to scan a document and do not have scanner handy, you can take a photograph of the document with webcam, and embed the JPEG into PDF - effectively works as a scanner.