Convert files written in python etc. to pdf with syntax highlighting

Bad Request

Thing you want to do

Convert source code like hogehoge.py to pdf file with syntax highlighting

Background

Like the a2ps I used a long time ago

% cat hogehoge.txt | a2ps | lpr -Pprinter_name

For a while, I was looking for a tool that would allow me to print easily. But, I can't find a tool like this, so I had to make it myself.

I thought about using a pipe to feed the pdf file to the printer without creating it in vain, but I couldn't think of it. For the time being, I decided to output pdf.

policy

  1. Create a pdf file with one command
  2. Call pandoc from python for processing
  3. Add line numbers to the code

My environment

Hardware & OS

  1. Macbook Pro (13-inch 2019, Four Thunderbolt 3 ports)
  2. 2.8GHz Quad Core Intel Core i7
  3. RAM 16GB
  4. macOS Catalina 10.15.4

software

  1. LuaLaTeX (This is LuaTeX, Version 1.10.0 (TeX Live 2019))
  2. pandoc (pandoc 2.2.3.2)
  3. python (Python 3.7.7 (default, Mar 23 2020, 17:31:31))

Create a chat

I will paste the sauce. It's better if you're doing weird things or doing this! We would appreciate it if you could give us your opinions.

code2pdf


#!/usr/bin/env python
import sys
import os
import subprocess

if len(sys.argv) < 2:
    print('Usage: %s FILENAME' % (sys.argv[0]))
    sys.exit()

args = sys.argv
filename = sys.argv[1]
extension = filename.rsplit('.',1)

if extension[1] == 'py':
    LANG = '{.python .numberLines}'
elif extension[1] == 'sh':
    LANG = '{.sh .numberLines}'
elif extension[1] == 'html':
    LANG = '{.html .numberLines}'
elif extension[1] == 'htm':
    LANG = '{.html .numberLines}'
else:
    LANG = ''

f = open(filename)
body = f.read()
f.close()
data_out = '# ' + filename + '\n' + '```'+ LANG +'\n' + body + '\n```'

subprocess.run(['pandoc',\
                '-o',extension[0]+'.pdf',\
                '--pdf-engine=lualatex',\
                '-V', 'documentclass=bxjsarticle',\
                '-V', 'classoption=pandoc,jafont=ipaex',\
                '--highlight-style=kate',\
#                '-H', '~/local/header.tex', #Write to preamble
                '-V', 'linestretch:0.75',\
                '-V', 'pagestyle:empty',\
                '-V', 'geometry:top=8truemm',\
                '-V', 'geometry:bottom=12truemm',\
                '-V', 'geometry:left=20truemm',\
                '-V', 'geometry:right=12truemm',\
                '-V', 'papersize=a4',\
                '-V', 'fontsize:9pt'],\
                input=data_out, text=True, encoding='UTF-8')

How to use

$ code2pdf hogehoge.py

finish

A screen capture of the above code in pdf.

スクリーンショット 2020-04-10 7.19.23.png

You can change the color of syntax highlight.

Currently available settings can be found with the --list-highlight-styles option. The execution result in my environment is as follows.

$ pandoc --list-highlight-styles
pygments
tango
espresso
zenburn
kate
monochrome
breezedark
haddock

There is a color sample on this page.

pandoc_highlight

Please also check.

Future tasks

  1. Use a pipe to pour directly into the printer
  2. Review font settings to make it easier to read

Recommended Posts

Convert files written in python etc. to pdf with syntax highlighting
Convert the image in .zip to PDF with Python
Convert markdown to PDF in Python
Convert PDF files to PNG files with GIMP
Convert HEIC files to PNG files with Python
Convert FBX files to ASCII <-> BINARY in Python
Convert PDF to image (JPEG / PNG) with Python
Convert PDFs to images in bulk with Python
Batch convert PSD files in directory to PDF
How to convert / restore a string with [] in python
Integrate PDF files with Python
How to add page numbers to PDF files (in Python)
Convert list to DataFrame with python
Read files in parallel with Python
Convert PDF to image with ImageMagick
Python script written in PyTorch is converted to exe with PyInstaller
Try logging in to qiita with Python
Convert memo at once with Python 2to3
Convert from PDF to CSV with pdfplumber
Convert psd file to png in Python
Convert Excel data to JSON with python
Convert Hiragana to Romaji with Python (Beta)
How to work with BigQuery in Python
Convert FX 1-minute data to 5-minute data with Python
Convert Chinese numerals to Arabic numerals with Python
To work with timestamp stations in Python
Convert from Markdown to HTML in Python
Convert absolute URLs to relative URLs in Python
Sample to convert image to Wavelet with Python
[HOW TO] Easy way to debug when generating PDF files with PHP etc.
Add syntax highlighting for the Kv language to Spyder in the Python IDE
I want to convert a table converted to PDF in Python back to CSV
I made a script in python to convert .md files to Scrapbox format
with syntax (Python)
Convert files uploaded to Cloud Storage with Cloud Functions (Python) so that they are not garbled in Excel
[Python] Get the files in a folder with Python
[REAPER] How to play with Reascript in Python
Introduction to effectiveness verification Chapter 3 written in Python
Summary of how to import files in Python 3
[Automation] Extract the table in PDF with Python
Convert svg file to png / ico with Python
Read table data in PDF file with Python
Convert Windows epoch values to date with python
Convert UTF-8 CSV files to read in Excel
How to convert SVG to PDF and PNG [Python]
Log in to Yahoo Business with Selenium Python
Handle zip files with Japanese filenames in Python 3
Character encoding when dealing with files in Python 3
How to get the files in the [Python] folder
How to use tkinter with python in pyenv
Convert multiple jpg files to one PDF file
Upload files to Google Drive with Lambda (Python)
Convert exponential notation float to str in Python
Convert multiple proto files at once with python
Introduction to Effectiveness Verification Chapter 2 Written in Python
Convert cubic mesh code to WKT in Python
Convert strings to character-by-character list format with python
Create an API to convert PDF files to TIF images with FastAPI and Docker
Introducing the magical "jsii" that runs programs written in TypeScript with Python etc.
How to get a list of files in the same directory with python
Convert timezoned date and time to Unixtime in Python2.7