iText Document : Rotate the page

2019-09-17 14:01发布

问题:

After the rotation of the document I lose the order of my data in the page :

package com.mkyong.common.view;


    import java.io.File;
    import java.io.IOException;
    import java.util.Map;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import org.springframework.web.servlet.view.document.AbstractPdfView;
    import com.lowagie.text.Document;
    import com.lowagie.text.DocumentException;
    import com.lowagie.text.PageSize;
    import com.lowagie.text.Table;
    import com.lowagie.text.pdf.PdfWriter;
    import com.lowagie.text.Image;
    public class PdfRevenueReportView extends AbstractPdfView{

        @Override
        protected void buildPdfDocument(Map model, Document document,
            PdfWriter writer, HttpServletRequest request,
            HttpServletResponse response) throws Exception {

            Image im= Image.getInstance("D:\\tree2.png");
             // setSize
             im.scaleToFit(130, 150);


            Map<String,String> revenueData = (Map<String,String>) model.get("revenueData");

            Table table = new Table(2);
            table.addCell("Month");
            table.addCell("Revenue");

            for (Map.Entry<String, String> entry : revenueData.entrySet()) {
                table.addCell(entry.getKey());
                table.addCell(entry.getValue());
                    }
            document.setPageSize(PageSize.A4.rotate());
            document.newPage();
            document.add(im);
            document.add(table);

        } 
    }

give me this :

and when i change the position of these two lines :

document.setPageSize(PageSize.A4.rotate());
document.newPage();

it return to the default position. Where is the problem ?

Thank you.

回答1:

Try this:

Document document = new Document(PageSize.A4.rotate());


回答2:

Resolved by this way :

            document.setPageSize(PageSize.A4.rotate());
        document.open();
        document.newPage();

thank you @Alex.



回答3:

Here is the code to rotate pages in (the new) itext 7:

    PdfDocument pdfDoc = new PdfDocument(new PdfReader(src), new PdfWriter(dest));

    for (int i = 1; i <= pdfDoc.getNumberOfPages(); i++) {
        PdfPage page = pdfDoc.getPage(i);
        page.setRotation(180);
    }

    pdfDoc.close();