Command line concatenate PDFs on OS X

A great post at http://gotofritz.net/blog/howto/joining-pdf-files-in-os-x-from-the-command-line/ which does what it says on the tin.

He explains how to link to a python script included in OS X since some years ago so as to make concatenating PDFs as easy as typing

pdfconcat -o output.pdf *.pdf

The heavy lifting is all done with calls to OS X Quartz.CoreGraphics module so this isn't going to work on other platforms, but for the curious it demonstrates how easily you can do such stuff on OS X.

#! /usr/bin/python
#
# join
#   Joing pages from a a collection of PDF files into a single PDF file.
#
#   join [--output <file>] [--shuffle] [--verbose]"
#
#   Parameter:
#
#   --shuffle
#	Take a page from each PDF input file in turn before taking another from each file.
#	If this option is not specified then all of the pages from a PDF file are appended
#	to the output PDF file before the next input PDF file is processed.
#
#   --verbose
#   Write information about the doings of this tool to stderr.
#
import sys
import os
import getopt
import tempfile
import shutil
from CoreFoundation import *
from Quartz.CoreGraphics import *

verbose = False

def createPDFDocumentWithPath(path):
	global verbose
	if verbose:
		print "Creating PDF document from file %s" % (path)
	return CGPDFDocumentCreateWithURL(CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, path, len(path), False))

def writePageFromDoc(writeContext, doc, pageNum):

	global verbose
	page = CGPDFDocumentGetPage(doc, pageNum)
	if page:
		mediaBox = CGPDFPageGetBoxRect(page, kCGPDFMediaBox)
		if CGRectIsEmpty(mediaBox):
			mediaBox = None
			
		CGContextBeginPage(writeContext, mediaBox)
		CGContextDrawPDFPage(writeContext, page)
		CGContextEndPage(writeContext)
		if verbose:
			print "Copied page %d from %s" % (pageNum, doc)

def shufflePages(writeContext, docs, maxPages):
	
	for pageNum in xrange(1, maxPages + 1):
		for doc in docs:
			writePageFromDoc(writeContext, doc, pageNum)
				
def append(writeContext, docs, maxPages):

	for doc in docs:
		for pageNum in xrange(1, maxPages + 1) :
			writePageFromDoc(writeContext, doc, pageNum)

def main(argv):

	global verbose

	# The PDF context we will draw into to create a new PDF
	writeContext = None

	# If True then generate more verbose information
	source = None
	shuffle = False
	
	# Parse the command line options
	try:
		options, args = getopt.getopt(argv, "o:sv", ["output=", "shuffle", "verbose"])

	except getopt.GetoptError:
		usage()
		sys.exit(2)

	for option, arg in options:

		if option in ("-o", "--output") :
			if verbose:
				print "Setting %s as the destination." % (arg)
			writeContext = CGPDFContextCreateWithURL(CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, arg, len(arg), False), None, None)

		elif option in ("-s", "--shuffle") :
			if verbose :
				print "Shuffle pages to the output file."
			shuffle = True

		elif option in ("-v", "--verbose") :
			print "Verbose mode enabled."
			verbose = True

		else :
			print "Unknown argument: %s" % (option)
	
	if writeContext:
		# create PDFDocuments for all of the files.
		docs = map(createPDFDocumentWithPath, args)
		
		# find the maximum number of pages.
		maxPages = 0
		for doc in docs:
			if CGPDFDocumentGetNumberOfPages(doc) > maxPages:
				maxPages = CGPDFDocumentGetNumberOfPages(doc)
	
		if shuffle:
			shufflePages(writeContext, docs, maxPages)
		else:
			append(writeContext, docs, maxPages)
		
		CGPDFContextClose(writeContext)
		del writeContext
		#CGContextRelease(writeContext)
    
def usage():
	print "Usage: join [--output <file>] [--shuffle] [--verbose]"

if __name__ == "__main__":
	main(sys.argv[1:])

Visual Studio 2013 Command Prompt Here for Windows Explorer Context Menu

To get a Visual Studio 2013 Command Prompt Here as a Context Menu (i.e., Right Click Menu) item in Windows Explorer, save this snippet to a .reg file and double click to import it into your registry:

Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Folder\shell\Command Line VS2013]
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Folder\shell\Command Line VS2013\command]
@="cmd.exe /k echo on & pushd \"%1\" & \"C:\\Program Files (x86)\\Microsoft Visual Studio 12.0\\Common7\\Tools\\VsDevCmd.bat\"" 

If you prefer to manually create the key path in RegEdit and add the command as the default value, drop the outermost quotes and the backslash escaping:

cmd.exe /k echo on & pushd "%1" & "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\VsDevCmd.bat"

Mono MVC System.UnauthorizedAccessException Access to the path “/Library/Frameworks/Mono.framework/Versions/…/etc/mono/registry” is denied

Is an error you are likely to see if you run a Visual Studio MVC template in Mono. There are two options for fixing it.

  • Do this from the command line:
    sudo mkdir /Library/Frameworks/Mono.framework/Versions/3.2.5/etc/mono/registry
    sudo chmod g+rwx /Library/Frameworks/Mono.framework/Versions/3.2.5/etc/mono/registry

    (replacing 3.2.5 with your mono version, which you get at the command line with mono --version)

  • Or delete the reference to Microsoft.Web.Infrastructure.dll from the project and delete it from the bin directory too.

The important difference is that deleting Microsoft.Web.Infrastructure.dll will stop your project working on .Net, so the registry access is simpler for cross-platformers. Another option for cross-platform project files would be something like this in the .csproj file:

<Target Name="AfterBuild">
    <Delete Files="$(WebProjectOutputDir)\bin\Microsoft.Web.Infrastructure.dll" Condition=" '$(OS)' != 'Windows_NT'" />
  </Target>

I prefer the 'grant access to the registry approach' myself but it does mean having to re-run the 2 line script for every new version of mono.

Visual Studio Template ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588

If you use the VS template to create a new 'internet' web application, then the template includes code for Asp.Net simple membership. But the template is written for SqlExpress. If you instead have a full SQL Server install on your machine it won't work.

The first exception you might see when debugging in visual studio is,

Exception has been thrown by the target of an invocation.

or if you aren't debugging you might see

The system cannot find the file specified

neither of which help at all.

so first, change the connection string in web.config to use your local SQL Server:

<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-MvcApplication1-20140225162244;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-MvcApplication1-20140225162244.mdf" providerName="System.Data.SqlClient" />

changing the connectionString's Data Source property to Data Source=.;

Now you might get the same or a different exception message:

The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588

but the linked page doesn't tell you how to fix it.

The inner exception is more helpful:

Directory lookup for the file "c:\...etc...\MvcApplication1\App_Data\aspnet-MvcApplication1-20140225162244.mdf" failed with the operating system error 5(Access is denied.).
CREATE DATABASE failed. Some file names listed could not be created. Check related errors.

Which tells you that the login account under which SQL Server is running doesn't have write permissions to the directory in which you write you code. It does have write permissions in the SQL Server data directory, for instance C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA so you'd think that by looking at that directory to see what user it runs under you'd be able to give it permissions.

Almost. The Explorer GUI Security tab showed me a usergroup called 'MSSQLSERVER' but if you try to give permissions to that group you'll find it doesn't exist. More helpful is the command line:

cacls "C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL"

which, if you look carefully at the output,

C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL 
    CREATOR OWNER:(OI)(CI)(IO)F
    NT AUTHORITY\SYSTEM:(OI)(CI)F
    BUILTIN\Administrators:(OI)(CI)F
    BUILTIN\Users:(OI)(CI)R
    NT SERVICE\MSSQLSERVER:(OI)(CI)R

shows you that you the actual name is NT SERVICE\MSSQLSERVER

So I gave modify permissions on my App_Data directory to NT SERVICE\MSSQLSERVER (I carefully copy-pasted the full name) and it worked.