Peter Huson
Peter Huson

Reputation: 55

PDFBox printing with PrintPDF command line tool

I am using DHL Shipping (XML) API in order to request DHL shipments and automatically print the responded shipping label.

This is how the system works:

The DHL response XML contains a base64-encoded pdf that contains:

Page 1. The Shipping Label (Prints on a sticker which is put on the package)

Page 2. The Archive Document (Needs to be printed separately and given to the shipping courier)

In order to separate the two pdfs, I first decode the base64, then execute a PDFSplit using PDFBox command-line tools, and finally print each respective document at their respective printer:

$filename = "dhlexpress_labels/".date("Ymd_his")."_{$_REQUEST['id']}.pdf";
//Get the pdf response from DHL
$data = file_get_contents("path/dhl_request_shipment.php?".http_build_query($_REQUEST));
//Put decoded data in the file
file_put_contents($filename,base64_decode($data));
//Split the file into two
$exec = 'java pdfbox-app-1.8.3.jar PDFSplit -split 1 ' . $filename;
exec($exec);
//Print each file
$exec = 'java pdfbox-app-1.8.3.jar PrintPDF -silentPrint -printerName DHLPrinter ' . str_replace('.pdf',-0.'.pdf',$filename);
exec($exec);
$exec = 'java pdfbox-app-1.8.3.jar PrintPDF -silentPrint -printerName PaperPrinter ' . str_replace('.pdf',-1.'.pdf',$filename);
exec($exec);

The problem is this: The response from DHL contains a pdf that has the dimensions of an 8"x4" sticker, which prints perfectly on the DHLPrinter, but on the PaperPrinter it doesn't print the left and top 5mm of the label. See attached picture:

Margins not printed

I think this happens because the margins are overridden by the pdf somehow, leading to the pdf moving outside the printable area.

Does anyone know of a way to fix this? I want the printing to be completely automated and will stop at no lengths to do so. I'm just wondering if anyone has any creative ideas about how to edit the pdf margins.

Upvotes: 1

Views: 1423

Answers (1)

Peter Huson
Peter Huson

Reputation: 55

I figured out a solution. Using OverlayPDF, I overlay the archive document onto a blank PDF and it shows up in the middle like this: Centered Label

I just added these two lines of code and it worked like a charm:

$exec = java -jar pdfbox-app-2.0.3-20160908.164926-191.jar OverlayPDF blank.pdf '. str_replace('.pdf','-1'.'.pdf',$filename) .' '. str_replace('.pdf','-1'.'.pdf',$filename);
exec($exec);

I tried using the 'orientation' attribute of PrintPDF, but it actually made it smaller: Orientation: vertical Orientation: horizontal was totally messed up. Picture is included in comment below.

Upvotes: 1

Related Questions