Question

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?

Was it helpful?

Solution

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á!

OTHER TIPS

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.

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top