24

How I can change the orientation of my pdf file which is generated with Wkhtmltopdf. I invoke it in PHP like following:

$file = fopen("tmp/html/pdfTmp_$numRand.html", 
    "w") or exit("Unable to open file!");
fwrite($file, $html);
fclose($file);

exec("..\library\wkhtmltopdf\wkhtmltopdf " . 
    "tmp/html/pdfTmp_$numRand.html tmp/pdf/pdfTmp_$numRand.pdf");

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header("Content-Disposition: attachment; filename=".$nom."_".$residence.".pdf");
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize("tmp/pdf/pdfTmp_$numRand.pdf"));
ob_clean();
flush();
readfile("tmp/pdf/pdfTmp_$numRand.pdf");

$html contains my whole page in html, and this opens a temporary file.

This generates a .pdf in portrait orientation. I know wkhtlktopdf has an option -O landscape to change orientation, but I don't know where and how I can write this in my PHP script. I'm using Windows 7.

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Daykeras
  • 253
  • 1
  • 2
  • 4
  • Pass the two flags `-O landscape` right after the wkhtmltopdf command, for example: `wkhtmltopdf -O landscape foobar.html foobar.pdf` – Eric Leschinski Apr 15 '17 at 04:57

3 Answers3

37

Option -O landscape will do the trick.

Just chage

exec("..\library\wkhtmltopdf\wkhtmltopdf tmp/html/pdfTmp_$numRand.html tmp/pdf/pdfTmp_$numRand.pdf");

to something like

exec("..\library\wkhtmltopdf\wkhtmltopdf -O landscape tmp/html/pdfTmp_$numRand.html tmp/pdf/pdfTmp_$numRand.pdf");
Mantas
  • 4,259
  • 2
  • 27
  • 32
4

I think this is also worth mentioning here:

I was having trouble with this too but I had set --orientation "Landscape" and had also set the --page-height '210mm' and --page-width '297mm'

My pdf's kept coming out in Portrait, very frustrating.

I was being too explicit. Taking out the page-height and page-width options resolved the issue for me

DamienB
  • 344
  • 3
  • 4
  • 3
    Little logic trap there. If your Width is larger than your Height, then Landscape will give you what looks like a Portrait orientation (because it swaps the width and height). – DylanYoung Dec 13 '17 at 18:28
2

this worked with me

import pdfkit

config = pdfkit.configuration(wkhtmltopdf="C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe")

options = {
    'orientation':'Landscape'
}

pdfkit.from_file("C:\\output.html","C:\\output.pdf", configuration=config,options=options)
azzmi
  • 21
  • 2