Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Both landscape and portrait for pdf with Flying Saucer/iText

Tags:

pdf

itext

Is there a way to set different page styles with Flying Saucer/iText? I need to have the first couple of pages in landscape, then switch to portrait at a certain page and out.

Any ideas?

like image 777
peirix Avatar asked Mar 05 '09 08:03

peirix


3 Answers

Nevermind, found the answer. For anyone interested, this is how you do it:

@page land { size:landscape; }
@page port { size:portrait; }
.landscapePage { page:land; }
.portraitPage { page:port; }

voilá!

like image 82
peirix Avatar answered Nov 08 '22 03:11

peirix


For anyone still stuck with the problem Derek mentioned, I've found that I need to explicitly set a width on the element that is switching its layout. So with the example div

<div class="portraitPage">
    <p>Some page content in portrait</p>
</div>
<div class="landscapePage">
    <p>Some page content in landscape</p>
</div>

it will correctly format a portrait page followed by a landscape page, but the content in landscape page will only be as wide as the portrait page, even if the @page land declaration contains a width. What I needed was to set the width directly on the div that has the relevant class applied, so the declaration is something more like

.landscapePage { page:land; width: 29.7cm; }

Be careful though that the width should take into account any margins or padding applied via the @page declaration block.

like image 28
Marcus Avatar answered Nov 08 '22 04:11

Marcus


You can handle your page size dynamically at run time. Please follow the following step

  1. Add extra parameter for page type e.g landscape or portrait in pageType param
  2. Add following code in your style tag when you are generating your html at server side for e.g
FileOutputStream fos = new FileOutputStream(file);
ITextRenderer renderer = new ITextRenderer();
StringBuilder htmls = new StringBuilder();
htmls.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
htmls.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">");
htmls.append("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
htmls.append("<head><style type=\"text/css\">");
htmls.append("@page{ size: "+request.getParameter("pageType")}");
htmls.append("</style></head>");
htmls.append("<body><div>dynamic pdf data</div></body></html>");
renderer.getFontResolver().addFont("C:\\Windows\\Fonts\\Calibri.ttf","UTF-8",BaseFont.NOT_EMBEDDED);
renderer.setDocumentFromString(htmls.toString());
renderer.layout();
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + ".pdf\"");
renderer.createPDF(outputStream);
renderer.createPDF(fos);
like image 20
shrey Avatar answered Nov 08 '22 05:11

shrey