Example usage for org.apache.pdfbox.pdmodel PDPage setRotation

List of usage examples for org.apache.pdfbox.pdmodel PDPage setRotation

Introduction

In this page you can find the example usage for org.apache.pdfbox.pdmodel PDPage setRotation.

Prototype

public void setRotation(int rotation) 

Source Link

Document

This will set the rotation for this page.

Usage

From source file:dtlgenerator.myDataReader.java

public void PdfGenerator(String pdfFileNameBase, List<String> cycles) throws IOException, COSVisitorException {
    GlobalVar.dirMake(new File(pdfFileNameBase)); //create a folder with the same name

    int rowCount = 0;
    int pageCount = 1;
    PDPage page; //default size PAGE_SIZE_A4
    PDPageContentStream stream;//w  ww  .j a  v  a  2  s. c  om
    //page.setRotation(90); //counterclock wise rotate 90 degree  ////left hand rule

    //        stream.setFont(PDType1Font.COURIER, FONT_SIZE);
    String lastUpdate = null;
    String lastCycle = null;
    System.out.println("DTL_DATA keyset:" + DTL_DATA.keySet());
    System.out.println("Cycles empty? " + cycles.isEmpty());
    System.out.println(cycles);
    for (String updateDate : DTL_DATA.keySet()) {
        Map<String, List<String>> thisDTData = DTL_DATA.get(updateDate);
        lastUpdate = updateDate;
        System.out.println("thisDT_DATA keyset:" + thisDTData.keySet());
        for (String cycle : thisDTData.keySet()) {
            if (cycles.isEmpty() || cycles.contains(cycle)) {
                PDDocument pdf = new PDDocument();
                lastCycle = cycle;
                List<String> thisCycle = thisDTData.get(cycle);
                pageCount = 1; // new cycle, restart page num
                page = new PDPage(); //page break
                stream = new PDPageContentStream(pdf, page, true, false);
                stream.beginText();
                page.setRotation(PAGE_ROT_DEGREE);
                //stream.setFont(PDType1Font.COURIER, FONT_SIZE);
                addBigFontUpdateNumberAndCycle(updateDate, cycle, stream);
                stream.setFont(PDType1Font.COURIER, FONT_SIZE);
                // stream.setFont(PDType1Font.
                int thisCycleRowCount = 0;
                for (String row : thisCycle) {
                    if (thisCycleRowCount > MAX_NUM_TRANS) {
                        //close the current page
                        setupFootNote(stream, pageCount, cycle, updateDate);
                        pageCount++;
                        stream.endText();
                        stream.close();
                        pdf.addPage(page);

                        // start a new page
                        page = new PDPage();
                        stream = new PDPageContentStream(pdf, page, true, false);
                        page.setRotation(PAGE_ROT_DEGREE);
                        stream.beginText();
                        stream.setFont(PDType1Font.COURIER, FONT_SIZE);
                        thisCycleRowCount = 0;
                    }
                    stream.setTextRotation(TEXT_ROT_RAD, TRANS_X + thisCycleRowCount * INVERVAL_X, TRANS_Y);
                    stream.drawString(row);
                    thisCycleRowCount++;
                    //System.out.println("Update:" + updateDate + " Cycle: " + cycle + " " + row);
                }
                setupFootNote(stream, pageCount, lastCycle, lastUpdate);
                stream.endText();
                stream.close();
                pdf.addPage(page);
                String pdfFileName = pdfFileNameBase + "\\DTL UPDT " + updateDate + " " + cycle + ".pdf";

                pdf.save(pdfFileName);
                pdf.close();
            }
        }
    }

    // pdf.save(pdfFileName);        
    // pdf.close();      
}

From source file:merge_split.MergeSplit.java

License:Apache License

private void RotateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RotateButtonActionPerformed
    try {/*  w  w w.  j  a v  a 2  s. c o  m*/

        PDDocument samplePdf = new PDDocument();
        File file = new File(RotateFileField.getText());
        PDDocument doc1;
        if (rotatecode.equals("ok")) {
            doc1 = PDDocument.load(file);
        } else {
            doc1 = PDDocument.load(file, rotatecode);

        }
        doc1.setAllSecurityToBeRemoved(true);
        TreeSet tree = findPages(RotatePagesField.getText());
        for (int j = 0; j < doc1.getNumberOfPages(); j++) {
            PDPage page = doc1.getPage(j);

            if (tree.contains(j + 1)) {

                if (Rotate90.isSelected()) {
                    page.setRotation(90);
                    samplePdf.addPage(page);
                } else if (Rotate180.isSelected()) {
                    page.setRotation(180);
                    samplePdf.addPage(page);
                } else if (Rotate270.isSelected()) {
                    page.setRotation(270);
                    samplePdf.addPage(page);
                }
            } else {
                samplePdf.addPage(page);

            }

        }

        System.out.println("Number:" + samplePdf.getNumberOfPages());

        String destination = RotateDestinationField.getText() + "\\" + RotateNameField.getText() + ".pdf";
        PDDocumentInformation info = samplePdf.getDocumentInformation();
        info.setAuthor(RotateAuthorField.getText());
        File output = new File(destination);

        samplePdf.save(output);

        samplePdf.close();
    } catch (IOException ex) {
        Logger.getLogger(MergeSplit.class.getName()).log(Level.SEVERE, null, ex);

        JOptionPane.showMessageDialog(null, "Your input is incorrect. Please fill all the fields.",
                "Input warning", JOptionPane.WARNING_MESSAGE);
    }
}

From source file:mil.tatrc.physiology.utilities.Excel2PDF.java

License:Apache License

public static void convert(String from, String to) throws IOException {
    FileInputStream xlFile = new FileInputStream(new File(from));
    // Read workbook into HSSFWorkbook
    XSSFWorkbook xlWBook = new XSSFWorkbook(xlFile);
    //We will create output PDF document objects at this point
    PDDocument pdf = new PDDocument();

    //pdf.addTitle();
    for (int s = 0; s < xlWBook.getNumberOfSheets(); s++) {
        XSSFSheet xlSheet = xlWBook.getSheetAt(s);
        Log.info("Processing Sheet : " + xlSheet.getSheetName());
        PDPage page = new PDPage(PDRectangle.A4);
        page.setRotation(90);
        pdf.addPage(page);//from  ww w .j av  a  2 s.  co  m
        PDRectangle pageSize = page.getMediaBox();
        PDPageContentStream contents = new PDPageContentStream(pdf, page);
        contents.transform(new Matrix(0, 1, -1, 0, pageSize.getWidth(), 0));// including a translation of pageWidth to use the lower left corner as 0,0 reference
        contents.setFont(PDType1Font.HELVETICA_BOLD, 16);
        contents.beginText();
        contents.newLineAtOffset(50, pageSize.getWidth() - 50);
        contents.showText(xlSheet.getSheetName());
        contents.endText();
        contents.close();

        int rows = xlSheet.getPhysicalNumberOfRows();
        for (int r = 0; r < rows; r++) {
            XSSFRow row = xlSheet.getRow(r);
            if (row == null)
                continue;
            int cells = row.getPhysicalNumberOfCells();
            if (cells == 0)
                continue;// Add an empty Roe

        }
    }

    /*    
        //We will use the object below to dynamically add new data to the table
        PdfPCell table_cell;
        //Loop through rows.
        while(rowIterator.hasNext()) 
        {
          Row row = rowIterator.next(); 
          Iterator<Cell> cellIterator = row.cellIterator();
          while(cellIterator.hasNext()) 
          {
            Cell cell = cellIterator.next(); //Fetch CELL
            switch(cell.getCellType()) 
            { //Identify CELL type
              //you need to add more code here based on
              //your requirement / transformations
              case Cell.CELL_TYPE_STRING:
    //Push the data from Excel to PDF Cell
    table_cell=new PdfPCell(new Phrase(cell.getStringCellValue()));
    //feel free to move the code below to suit to your needs
    my_table.addCell(table_cell);
    break;
            }
            //next line
          }
        }
    */
    pdf.save(new File(to));
    pdf.close();
    xlWBook.close();
    xlFile.close(); //close xls
}

From source file:org.apache.fop.render.pdf.PDFRotateTestCase.java

License:Apache License

@Test
public void test() throws Exception {
    ImageConverterPDF2G2D i = new ImageConverterPDF2G2D();
    ImageInfo imgi = new ImageInfo("a", "b");
    PDDocument doc = new PDDocument();
    PDPage page = new PDPage();
    page.setRotation(90);
    doc.addPage(page);/*from  www . j  av a  2 s  . com*/
    Image img = new ImagePDF(imgi, doc);
    ImageGraphics2D ig = (ImageGraphics2D) i.convert(img, null);
    Rectangle2D rect = new Rectangle2D.Float(0, 0, 100, 100);

    PSGraphics2D g2d = new PSPDFGraphics2D(true);
    GraphicContext gc = new GraphicContext();
    g2d.setGraphicContext(gc);
    ig.getGraphics2DImagePainter().paint(g2d, rect);
    Assert.assertEquals(g2d.getTransform().getShearX(), 0.16339869281045735);
}

From source file:org.nmrfx.processor.gui.graphicsio.PDFWriter.java

License:Open Source License

public void create(boolean landScape, double width, double height, String fileName) throws GraphicsIOException {
    // the document
    this.landScape = landScape;
    this.fileName = fileName;
    doc = new PDDocument();
    try {//from  w  ww . jav  a2  s. c  o m
        PDPage page = new PDPage(PDRectangle.LETTER);
        doc.addPage(page);
        PDRectangle pageSize = page.getMediaBox();
        pageWidth = pageSize.getWidth();
        pageHeight = pageSize.getHeight();
        contentStream = new PDPageContentStream(doc, page, false, false);
        // add the rotation using the current transformation matrix
        // including a translation of pageWidth to use the lower left corner as 0,0 reference
        if (landScape) {
            page.setRotation(90);
            contentStream.transform(new Matrix(0, 1, -1, 0, pageWidth, 0));
        }
    } catch (IOException ioE) {
        throw new GraphicsIOException(ioE.getMessage());
    }
}

From source file:org.oscarehr.document.web.SplitDocumentAction.java

License:Open Source License

public ActionForward split(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    String docNum = request.getParameter("document");
    String[] commands = request.getParameterValues("page[]");

    Document doc = documentDAO.getDocument(docNum);

    //      String docdownload = oscar.OscarProperties.getInstance().getProperty("DOCUMENT_DIR");
    //      new File(docdownload);
    String docdownload = EDocUtil.getDocumentDir(doc.getDocfilename());

    String newFilename = doc.getDocfilename();
    String dbPrefix = EDocUtil.getDocumentPrefix(doc.getDocfilename());

    //      FileInputStream input = new FileInputStream(docdownload + doc.getDocfilename());
    FileInputStream input = new FileInputStream(EDocUtil.getDocumentPath(newFilename));
    PDFParser parser = new PDFParser(input);
    parser.parse();//from  www .  j  a v  a2  s  .c o  m
    PDDocument pdf = parser.getPDDocument();

    PDDocument newPdf = new PDDocument();

    List pages = pdf.getDocumentCatalog().getAllPages();

    if (commands != null) {
        for (String c : commands) {
            String[] command = c.split(",");
            int pageNum = Integer.parseInt(command[0]);
            int rotation = Integer.parseInt(command[1]);

            PDPage p = (PDPage) pages.get(pageNum - 1);
            p.setRotation(rotation);

            newPdf.addPage(p);
        }

    }

    //newPdf.save(docdownload + newFilename);

    if (newPdf.getNumberOfPages() > 0) {
        LoggedInInfo loggedInInfo = LoggedInInfo.loggedInInfo.get();

        //         EDoc newDoc = new EDoc("","", newFilename, "", loggedInInfo.loggedInProvider.getProviderNo(), doc.getDoccreator(), "", 'A', oscar.util.UtilDateUtilities.getToday("yyyy-MM-dd"), "", "", "demographic", "-1",0);
        EDoc newDoc = new EDoc("", "", EDocUtil.getDocumentFileName(newFilename), "",
                loggedInInfo.loggedInProvider.getProviderNo(), doc.getDoccreator(), "", 'A',
                oscar.util.UtilDateUtilities.getToday("yyyy-MM-dd"), "", "", "demographic", "-1", 0);
        newDoc.setFileName(dbPrefix + '.' + newDoc.getFileName());
        newDoc.setDocPublic("0");
        newDoc.setContentType("application/pdf");
        newDoc.setNumberOfPages(newPdf.getNumberOfPages());

        String newDocNo = EDocUtil.addDocumentSQL(newDoc);

        //         //newPdf.save(docdownload + newDoc.getFileName());
        System.gc(); //avoid Windows lock on channel
        newPdf.save(docdownload + EDocUtil.getDocumentFileName(newDoc.getFileName()));
        newPdf.close();

        WebApplicationContext ctx = WebApplicationContextUtils
                .getRequiredWebApplicationContext(request.getSession().getServletContext());
        ProviderInboxRoutingDao providerInboxRoutingDao = (ProviderInboxRoutingDao) ctx
                .getBean("providerInboxRoutingDAO");
        providerInboxRoutingDao.addToProviderInbox("0", newDocNo, "DOC");

        List<ProviderInboxItem> routeList = providerInboxRoutingDao.getProvidersWithRoutingForDocument("DOC",
                docNum);
        for (ProviderInboxItem i : routeList) {
            providerInboxRoutingDao.addToProviderInbox(i.getProviderNo(), newDocNo, "DOC");
        }

        providerInboxRoutingDao.addToProviderInbox(loggedInInfo.loggedInProvider.getProviderNo(), newDocNo,
                "DOC");

        QueueDocumentLinkDao queueDocumentLinkDAO = (QueueDocumentLinkDao) ctx.getBean("queueDocumentLinkDAO");
        Integer qid = 1;
        Integer did = Integer.parseInt(newDocNo.trim());
        queueDocumentLinkDAO.addToQueueDocumentLink(qid, did);

        ProviderLabRoutingDao providerLabRoutingDao = (ProviderLabRoutingDao) SpringUtils
                .getBean("providerLabRoutingDao");

        List<ProviderLabRoutingModel> result = providerLabRoutingDao.getProviderLabRoutingDocuments(docNum);
        if (!result.isEmpty()) {
            new ProviderLabRouting().route(newDocNo, result.get(0).getProviderNo(), "DOC");
        }

        PatientLabRoutingDao patientLabRoutingDao = (PatientLabRoutingDao) SpringUtils
                .getBean("patientLabRoutingDao");
        List<PatientLabRouting> result2 = patientLabRoutingDao.findDocByDemographic(docNum);

        if (!result2.isEmpty()) {
            PatientLabRouting newPatientRoute = new PatientLabRouting();

            newPatientRoute.setDemographicNo(result2.get(0).getDemographicNo());
            newPatientRoute.setLabNo(Integer.parseInt(newDocNo));
            newPatientRoute.setLabType("DOC");

            patientLabRoutingDao.persist(newPatientRoute);
        }

        DocumentDAO documentDao = (DocumentDAO) SpringUtils.getBean("documentDAO");
        CtlDocument result3 = documentDao.getCtrlDocument(Integer.parseInt(docNum));

        if (result3 != null) {
            CtlDocumentPK ctlDocumentPK = new CtlDocumentPK(Integer.parseInt(newDocNo), "demographic");
            CtlDocument newCtlDocument = new CtlDocument(ctlDocumentPK, result3.getModuleId());
            newCtlDocument.setStatus(result3.getStatus());
            documentDao.saveCtlDocument(newCtlDocument);
        }

    }

    pdf.close();
    input.close();

    return mapping.findForward("success");
}

From source file:org.oscarehr.document.web.SplitDocumentAction.java

License:Open Source License

public ActionForward rotate180(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    Document doc = documentDAO.getDocument(request.getParameter("document"));

    //      String docdownload = oscar.OscarProperties.getInstance().getProperty("DOCUMENT_DIR");
    String docdownload = EDocUtil.getDocumentPath(doc.getDocfilename());

    if (doc.getContenttype().equals("application/pdf")) {
        FileInputStream input = null;
        PDDocument pdf = null;//from w ww. j a v a 2  s .  c o m
        try {
            //      FileInputStream input = new FileInputStream(docdownload + doc.getDocfilename());
            input = new FileInputStream(docdownload);
            PDFParser parser = new PDFParser(input);
            parser.parse();
            pdf = parser.getPDDocument();
            int x = 1;
            for (Object p : pdf.getDocumentCatalog().getAllPages()) {
                PDPage pg = (PDPage) p;
                Integer r = (pg.getRotation() != null ? pg.getRotation() : 0);
                pg.setRotation((r + 180) % 360);

                ManageDocumentAction.deleteCacheVersion(doc, x);
                x++;
            }

            //      pdf.save(docdownload + doc.getDocfilename());
            pdf.save(docdownload);

        } finally {
            if (pdf != null)
                pdf.close();
            input.close();
        }

    } else if (doc.getContenttype().equals("image/jpg") || doc.getContenttype().equals("image/png")
            || doc.getContenttype().equals("image/gif")) {
        String documentDir = EDocUtil.getDocumentDir(doc.getDocfilename());
        File file = new File(documentDir + doc.getDocfilename());
        BufferedImage image = ImageIO.read(file);
        if (image == null)
            return null;
        BufferedImage rotatedImage = new BufferedImage(image.getHeight(), image.getWidth(),
                BufferedImage.TYPE_INT_ARGB);

        String suffix = null;
        String contentType = doc.getContenttype();
        if (contentType.equalsIgnoreCase("image/jpg") || contentType.equalsIgnoreCase("image/jpeg")) {
            suffix = "jpg";
        } else if (contentType.equalsIgnoreCase("image/png")) {
            suffix = "png";
        } else if (contentType.equalsIgnoreCase("image/gif")) {
            suffix = "gif";
        }
        AffineTransform tx = AffineTransform.getScaleInstance(1, -1);
        tx = AffineTransform.getScaleInstance(-1, -1);
        tx.translate(-image.getWidth(null), -image.getHeight(null));
        AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
        image = op.filter(image, null);
        ImageIO.write(image, suffix, file);
    } else {
        //umknown type - does nothing
    }

    return null;
}

From source file:org.oscarehr.document.web.SplitDocumentAction.java

License:Open Source License

public ActionForward rotate90(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    Document doc = documentDAO.getDocument(request.getParameter("document"));

    FileInputStream input = new FileInputStream(EDocUtil.getDocumentPath(doc.getDocfilename()));
    PDFParser parser = new PDFParser(input);
    parser.parse();//from  w ww  . ja  va  2  s  .c  o m
    PDDocument pdf = parser.getPDDocument();
    int x = 1;
    for (Object p : pdf.getDocumentCatalog().getAllPages()) {
        PDPage pg = (PDPage) p;
        Integer r = (pg.getRotation() != null ? pg.getRotation() : 0);
        pg.setRotation((r + 90) % 360);

        ManageDocumentAction.deleteCacheVersion(doc, x);
        x++;
    }

    pdf.save(EDocUtil.getDocumentPath(doc.getDocfilename()));
    pdf.close();

    input.close();

    return null;

}

From source file:org.pdfsam.pdfbox.component.PdfRotator.java

License:Open Source License

/**
 * apply the rotation to the given page if necessary
 * //from   ww w  . ja  va 2  s.c om
 * @param pageNmber
 */
private void apply(int pageNmber) {
    PDPage page = document.getPage(pageNmber - 1);
    page.setRotation(rotation.addRotation(getRotation(page.getRotation())).getDegrees());
}

From source file:org.sejda.impl.pdfbox.component.PDDocumentHandler.java

License:Apache License

/**
 * Import an existing page to the underlying {@link PDDocument}
 * //from  w  w w.  j a v a2 s.  c  o  m
 * @param page
 * @throws TaskIOException
 */
public void importPage(PDPage page) throws TaskIOException {
    PDPage imported;
    try {
        imported = document.importPage(page);
    } catch (IOException e) {
        throw new TaskIOException("An error occurred copying the page.", e);
    }
    imported.setCropBox(page.findCropBox());
    imported.setMediaBox(page.findMediaBox());
    imported.setResources(page.findResources());
    imported.setRotation(page.findRotation());
}