Example usage for com.itextpdf.text BaseColor BaseColor

List of usage examples for com.itextpdf.text BaseColor BaseColor

Introduction

In this page you can find the example usage for com.itextpdf.text BaseColor BaseColor.

Prototype

public BaseColor(final int argb) 

Source Link

Document

Construct a BaseColor by setting the combined value.

Usage

From source file:controller.CCInstance.java

License:Open Source License

public final boolean signPdf(final String pdfPath, final String destination, final CCSignatureSettings settings,
        final SignatureListener sl) throws CertificateException, IOException, DocumentException,
        KeyStoreException, SignatureFailedException, FileNotFoundException, NoSuchAlgorithmException,
        InvalidAlgorithmParameterException {
    PrivateKey pk;/* w  w w.  j  a  va2  s.  c  o  m*/

    final PdfReader reader = new PdfReader(pdfPath);
    pk = getPrivateKeyFromAlias(settings.getCcAlias().getAlias());

    if (getCertificationLevel(pdfPath) == PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED) {
        String message = Bundle.getBundle().getString("fileDoesNotAllowChanges");
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, false, message);
        }
        throw new SignatureFailedException(message);
    }

    if (reader.getNumberOfPages() - 1 < settings.getPageNumber()) {
        settings.setPageNumber(reader.getNumberOfPages() - 1);
    }

    if (null == pk) {
        String message = Bundle.getBundle().getString("noSmartcardFound");
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, false, message);
        }
        throw new CertificateException(message);
    }

    if (null == pkcs11ks.getCertificateChain(settings.getCcAlias().getAlias())) {
        String message = Bundle.getBundle().getString("certificateNullChain");
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, false, message);
        }
        throw new CertificateException(message);
    }
    final ArrayList<Certificate> embeddedCertificateChain = settings.getCcAlias().getCertificateChain();
    final Certificate owner = embeddedCertificateChain.get(0);
    final Certificate lastCert = embeddedCertificateChain.get(embeddedCertificateChain.size() - 1);

    if (null == owner) {
        String message = Bundle.getBundle().getString("certificateNameUnknown");
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, false, message);
        }
        throw new CertificateException(message);
    }

    final X509Certificate X509C = ((X509Certificate) lastCert);
    final Calendar now = Calendar.getInstance();
    final Certificate[] filledMissingCertsFromChainInTrustedKeystore = getCompleteTrustedCertificateChain(
            X509C);

    final Certificate[] fullCertificateChain;
    if (filledMissingCertsFromChainInTrustedKeystore.length < 2) {
        fullCertificateChain = new Certificate[embeddedCertificateChain.size()];
        for (int i = 0; i < embeddedCertificateChain.size(); i++) {
            fullCertificateChain[i] = embeddedCertificateChain.get(i);
        }
    } else {
        fullCertificateChain = new Certificate[embeddedCertificateChain.size()
                + filledMissingCertsFromChainInTrustedKeystore.length - 1];
        int i = 0;
        for (i = 0; i < embeddedCertificateChain.size(); i++) {
            fullCertificateChain[i] = embeddedCertificateChain.get(i);
        }
        for (int f = 1; f < filledMissingCertsFromChainInTrustedKeystore.length; f++, i++) {
            fullCertificateChain[i] = filledMissingCertsFromChainInTrustedKeystore[f];
        }
    }

    // Leitor e Stamper
    FileOutputStream os = null;
    try {
        os = new FileOutputStream(destination);
    } catch (FileNotFoundException e) {
        String message = Bundle.getBundle().getString("outputFileError");
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, false, message);
        }
        throw new IOException(message);
    }

    // Aparncia da Assinatura
    final char pdfVersion;
    switch (Settings.getSettings().getPdfVersion()) {
    case "/1.2":
        pdfVersion = PdfWriter.VERSION_1_2;
        break;
    case "/1.3":
        pdfVersion = PdfWriter.VERSION_1_3;
        break;
    case "/1.4":
        pdfVersion = PdfWriter.VERSION_1_4;
        break;
    case "/1.5":
        pdfVersion = PdfWriter.VERSION_1_5;
        break;
    case "/1.6":
        pdfVersion = PdfWriter.VERSION_1_6;
        break;
    case "/1.7":
        pdfVersion = PdfWriter.VERSION_1_7;
        break;
    default:
        pdfVersion = PdfWriter.VERSION_1_7;
    }

    final PdfStamper stamper = (getNumberOfSignatures(pdfPath) == 0
            ? PdfStamper.createSignature(reader, os, pdfVersion)
            : PdfStamper.createSignature(reader, os, pdfVersion, null, true));

    final PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
    appearance.setSignDate(now);
    appearance.setReason(settings.getReason());
    appearance.setLocation(settings.getLocation());
    appearance.setCertificationLevel(settings.getCertificationLevel());
    appearance.setSignatureCreator(SIGNATURE_CREATOR);
    appearance.setCertificate(owner);

    final String fieldName = settings.getPrefix() + " " + (1 + getNumberOfSignatures(pdfPath));
    if (settings.isVisibleSignature()) {
        appearance.setVisibleSignature(settings.getPositionOnDocument(), settings.getPageNumber() + 1,
                fieldName);
        appearance.setRenderingMode(PdfSignatureAppearance.RenderingMode.DESCRIPTION);
        if (null != settings.getAppearance().getImageLocation()) {
            appearance.setImage(Image.getInstance(settings.getAppearance().getImageLocation()));
        }

        com.itextpdf.text.Font font = new com.itextpdf.text.Font(FontFactory
                .getFont(settings.getAppearance().getFontLocation(), BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 0)
                .getBaseFont());

        font.setColor(new BaseColor(settings.getAppearance().getFontColor().getRGB()));
        if (settings.getAppearance().isBold() && settings.getAppearance().isItalic()) {
            font.setStyle(Font.BOLD + Font.ITALIC);
        } else if (settings.getAppearance().isBold()) {
            font.setStyle(Font.BOLD);
        } else if (settings.getAppearance().isItalic()) {
            font.setStyle(Font.ITALIC);
        } else {
            font.setStyle(Font.PLAIN);
        }

        appearance.setLayer2Font(font);
        String text = "";
        if (settings.getAppearance().isShowName()) {
            if (!settings.getCcAlias().getName().isEmpty()) {
                text += settings.getCcAlias().getName() + "\n";
            }
        }
        if (settings.getAppearance().isShowReason()) {
            if (!settings.getReason().isEmpty()) {
                text += settings.getReason() + "\n";
            }
        }
        if (settings.getAppearance().isShowLocation()) {
            if (!settings.getLocation().isEmpty()) {
                text += settings.getLocation() + "\n";
            }
        }
        if (settings.getAppearance().isShowDate()) {
            DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            SimpleDateFormat sdf = new SimpleDateFormat("Z");
            text += df.format(now.getTime()) + " " + sdf.format(now.getTime()) + "\n";
        }
        if (!settings.getText().isEmpty()) {
            text += settings.getText();
        }

        PdfTemplate layer2 = appearance.getLayer(2);
        Rectangle rect = settings.getPositionOnDocument();
        Rectangle sr = new Rectangle(rect.getWidth(), rect.getHeight());
        float size = ColumnText.fitText(font, text, sr, 1024, PdfWriter.RUN_DIRECTION_DEFAULT);
        ColumnText ct = new ColumnText(layer2);
        ct.setRunDirection(PdfWriter.RUN_DIRECTION_DEFAULT);
        ct.setAlignment(Element.ALIGN_MIDDLE);
        int align;
        switch (settings.getAppearance().getAlign()) {
        case 0:
            align = Element.ALIGN_LEFT;
            break;
        case 1:
            align = Element.ALIGN_CENTER;
            break;
        case 2:
            align = Element.ALIGN_RIGHT;
            break;
        default:
            align = Element.ALIGN_LEFT;
        }

        ct.setSimpleColumn(new Phrase(text, font), sr.getLeft(), sr.getBottom(), sr.getRight(), sr.getTop(),
                size, align);
        ct.go();
    } else {
        appearance.setVisibleSignature(new Rectangle(0, 0, 0, 0), 1, fieldName);
    }

    // CRL <- Pesado!
    final ArrayList<CrlClient> crlList = null;

    // OCSP
    OcspClient ocspClient = new OcspClientBouncyCastle();

    // TimeStamp
    TSAClient tsaClient = null;
    if (settings.isTimestamp()) {
        tsaClient = new TSAClientBouncyCastle(settings.getTimestampServer(), null, null);
    }

    final String hashAlg = getHashAlgorithm(X509C.getSigAlgName());

    final ExternalSignature es = new PrivateKeySignature(pk, hashAlg, pkcs11Provider.getName());
    final ExternalDigest digest = new ProviderDigest(pkcs11Provider.getName());

    try {
        MakeSignature.signDetached(appearance, digest, es, fullCertificateChain, crlList, ocspClient, tsaClient,
                0, MakeSignature.CryptoStandard.CMS);
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, true, "");
        }
        return true;
    } catch (Exception e) {
        os.flush();
        os.close();
        new File(destination).delete();
        if ("sun.security.pkcs11.wrapper.PKCS11Exception: CKR_FUNCTION_CANCELED".equals(e.getMessage())) {
            throw new SignatureFailedException(Bundle.getBundle().getString("userCanceled"));
        } else if ("sun.security.pkcs11.wrapper.PKCS11Exception: CKR_GENERAL_ERROR".equals(e.getMessage())) {
            throw new SignatureFailedException(Bundle.getBundle().getString("noPermissions"));
        } else if (e instanceof ExceptionConverter) {
            String message = Bundle.getBundle().getString("timestampFailed");
            if (sl != null) {
                sl.onSignatureComplete(pdfPath, false, message);
            }
            throw new SignatureFailedException(message);
        } else {
            if (sl != null) {
                sl.onSignatureComplete(pdfPath, false, Bundle.getBundle().getString("unknownErrorLog"));
            }
            controller.Logger.getLogger().addEntry(e);
        }
        return false;
    }
}

From source file:de.aidger.utils.pdf.BudgetReportConverter.java

License:Open Source License

/**
 * Adds a row, containing a course budget, to the table.
 * // w w w . j  a  va2s  .co  m
 * @param objectArray
 *            The course budget.
 * @return The table containing the row.
 */
private PdfPTable addRow(Object[] objectArray) {
    try {
        Font tableContentFont = new Font(
                BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.EMBEDDED), 9);
        PdfPTable tableContent = new PdfPTable(new float[] { 0.3f, 0.15f, 0.15f, 0.15f, 0.15f, 0.10f });
        Color cellColor = new Color(255, 255, 255);
        if (Double.parseDouble(objectArray[4].toString()) == 0) {
            cellColor = new Color(252, 200, 150);
        }
        for (int i = 0; i < objectArray.length; i++) {
            PdfPCell cell = new PdfPCell(new Phrase(objectArray[i].toString(), tableContentFont));
            cell.setBackgroundColor(new BaseColor(cellColor));
            cell.setPaddingBottom(5);
            tableContent.addCell(cell);
        }
        return tableContent;
    } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

From source file:de.domjos.schooltools.helper.ApiHelper.java

License:Open Source License

public PDFBuilder exportTimeTableToPDF(PDFBuilder pdfBuilder, TimeTable timeTable, List<String> headers,
        SQLite sqLite) throws Exception {
    pdfBuilder.addTitle(timeTable.getTitle(), "header", Paragraph.ALIGN_CENTER);
    pdfBuilder.addEmptyLine(3);/*ww w.j  a v a2 s  .  co  m*/
    String content = "%s%n%s%n%s";
    String classTitle = "";
    if (timeTable.getSchoolClass() != null) {
        classTitle = this.context.getString(R.string.timetable_class) + ": "
                + timeTable.getSchoolClass().getTitle();
    }
    String yearTitle = "";
    if (timeTable.getYear() != null) {
        yearTitle = this.context.getString(R.string.mark_year) + ": " + timeTable.getYear().getTitle();
    }
    String description = "";
    if (!timeTable.getDescription().isEmpty()) {
        description = this.context.getString(R.string.sys_description) + "\n" + timeTable.getDescription();
    }
    content = String.format(content, yearTitle, classTitle, description);
    pdfBuilder.addParagraph("", content, "header", "CONTENT_PARAM");
    pdfBuilder.addEmptyLine(2);

    List<List<Map.Entry<String, BaseColor>>> tblCells = new LinkedList<>();
    List<Hour> hours = sqLite.getHours("");
    for (Hour hour : hours) {
        if (hour.isBreak()) {
            List<Map.Entry<String, BaseColor>> tblRows = new LinkedList<>();
            tblRows.add(new AbstractMap.SimpleEntry<>(hour.getStart() + " - " + hour.getEnd(), BaseColor.GRAY));
            for (int i = 0; i <= 6; i++) {
                tblRows.add(new AbstractMap.SimpleEntry<>("", BaseColor.GRAY));
            }
            tblCells.add(tblRows);
        } else {
            List<Map.Entry<String, BaseColor>> tblRows = new LinkedList<>();
            tblRows.add(
                    new AbstractMap.SimpleEntry<>(hour.getStart() + " - " + hour.getEnd(), BaseColor.WHITE));
            for (int i = 0; i <= 6; i++) {
                tblRows.add(new AbstractMap.SimpleEntry<>("", BaseColor.WHITE));
            }
            tblCells.add(tblRows);
        }
    }

    for (int column = 0; column <= timeTable.getDays().length - 1; column++) {
        Day day = timeTable.getDays()[column];
        int tmp = 0;
        if (day != null) {
            if (MainActivity.globals.getUserSettings().isTimeTableMode()) {
                Object[] objArray = day.getTeacherHour().values().toArray();
                int row = 0;
                for (Hour hour : hours) {
                    if (objArray.length < tmp + 1) {
                        break;
                    }
                    if (objArray[tmp] instanceof TeacherHour) {
                        for (Map.Entry<Hour, TeacherHour> entry : day.getTeacherHour().entrySet()) {
                            if (entry.getKey().getID() == hour.getID()) {
                                Subject subject = entry.getValue().getSubject();
                                String roomNumber = entry.getValue().getRoomNumber();
                                if (tblCells.get(row).get(0).getValue() != BaseColor.GRAY) {
                                    tblCells.get(row).set(column + 1, new AbstractMap.SimpleEntry<>(
                                            subject.getAlias() + "\n" + roomNumber,
                                            new BaseColor(Integer.parseInt(subject.getBackgroundColor()))));
                                    tmp++;
                                }
                                break;
                            }
                        }
                    }
                    row++;
                }
            } else {
                Object[] objArray = day.getPupilHour().values().toArray();
                int row = 0;
                for (Hour hour : hours) {
                    if (objArray.length < tmp + 1) {
                        break;
                    }
                    if (objArray[tmp] instanceof PupilHour) {
                        for (Map.Entry<Hour, PupilHour> entry : day.getPupilHour().entrySet()) {
                            if (entry.getKey().getID() == hour.getID()) {
                                Subject subject = entry.getValue().getSubject();
                                String roomNumber = entry.getValue().getRoomNumber();
                                if (tblCells.get(row).get(0).getValue() != BaseColor.GRAY) {
                                    tblCells.get(row).set(column + 1, new AbstractMap.SimpleEntry<>(
                                            subject.getAlias() + "\n" + roomNumber,
                                            new BaseColor(Integer.parseInt(subject.getBackgroundColor()))));
                                    tmp++;
                                }
                                break;
                            }
                        }
                    }
                    row++;
                }
            }
        }
    }

    pdfBuilder.addTable(headers, new float[] { 20.0f, 15.0f, 15.0f, 15.0f, 15.0f, 15.0f, 15.0f, 15.0f },
            tblCells);
    pdfBuilder.newPage();
    return pdfBuilder;
}

From source file:edu.cornell.mannlib.vitro.webapp.visualization.visutils.PDFDocument.java

License:Open Source License

public PDFDocument(String authorName, Map<String, Integer> yearToPublicationCount, Document document,
        PdfWriter pdfWriter) {/*from   ww w .java2 s.  c o m*/

    //        setPreferredSize(new Dimension(600,400));

    try {

        document.addTitle("PDF Pipeline iText Prototype");
        document.addAuthor(authorName);
        document.addSubject("This example tests text, color, image, transparency & table functionality.");
        document.addKeywords("text, color, image, transparency, table");
        document.addCreator("Standalone PDF Renderer using iText");

        Paragraph header = new Paragraph();

        Font pageHeaderStyle = FontFactory.getFont(FontFactory.TIMES_ROMAN, 15,
                Font.BOLDITALIC | Font.UNDERLINE);
        Font featureHeaderStyle = FontFactory.getFont(FontFactory.TIMES_ROMAN, 10, new BaseColor(Color.red));

        header.add(new Chunk("PDF Pipeline Prototype v2 using iText\n", pageHeaderStyle));

        header.setSpacingAfter(15f);

        document.add(header);

        Paragraph content = new Paragraph();

        content.add(new Chunk("Publication Count - Author Name - " + authorName, featureHeaderStyle));

        content.setSpacingAfter(15f);

        document.add(content);
        // step4

        PdfPTable publicationCount = createTable(yearToPublicationCount);

        document.add(publicationCount);

        content = new Paragraph();

        content.add(new Chunk("Transparency of Shapes", featureHeaderStyle));

        content.setSpacingAfter(15f);

        document.add(content);

        createTransparencyShapes(document, pdfWriter);

        createImage(document, pdfWriter, featureHeaderStyle);

    } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:edu.cornell.mannlib.vitro.webapp.visualization.visutils.PDFDocument.java

License:Open Source License

/**
 * Prints a square and fills half of it with a gray rectangle.
 * @param x/*from w w  w  . j a  va2s.c o  m*/
 * @param y
 * @param cb
 * @throws Exception
 */
public void pictureBackdrop(float x, float y, PdfContentByte cb) throws Exception {
    cb.setColorStroke(new BaseColor(Color.black));
    cb.setColorFill(new BaseColor(Color.gray));
    cb.rectangle(x, y, 100, 200);
    cb.fill();
    cb.setLineWidth(2);
    cb.rectangle(x, y, 200, 200);
    cb.stroke();
}

From source file:edu.cornell.mannlib.vitro.webapp.visualization.visutils.PDFDocument.java

License:Open Source License

/**
 * Prints 3 circles in different colors that intersect with eachother.
 * @param x/*www .j  av  a2s .co m*/
 * @param y
 * @param cb
 * @throws Exception
 */
public void pictureCircles(float x, float y, PdfContentByte cb) throws Exception {

    cb.saveState();
    PdfGState gs1 = new PdfGState();
    gs1.setFillOpacity(1.0f);
    cb.setGState(gs1);
    cb.setColorFill(new BaseColor(Color.red));
    cb.circle(x + 70, y + 70, 50);
    cb.fill();
    cb.restoreState();

    cb.setColorFill(new BaseColor(Color.yellow));
    cb.circle(x + 100, y + 130, 50);
    cb.fill();
    cb.setColorFill(new BaseColor(Color.blue));
    cb.circle(x + 130, y + 70, 50);
    cb.fill();
}

From source file:EplanPrinter.PDFPrint.java

License:Open Source License

public String insertSketch(String points, String color, String opac, int pageNum, int masterHeight,
        int masterWidth, int lineWeight, String lineStyle) throws DocumentException, IOException {
    float f = Float.valueOf(opac);
    PdfGState gs1 = new PdfGState();

    int t = points.indexOf("POLYGON");
    gs1.setFillOpacity(f);//from w ww  .j  a  v a 2s  .co m

    PdfContentByte fg = pds.getOverContent(pageNum);
    fg.setGState(gs1);
    float[] pointsSt = shatterSketches(points);
    color = "0x" + color.substring(1);
    Color c = Color.decode(color);

    fg.setLineWidth(lineWeight * getRatio(masterHeight, masterWidth, pageNum));
    if (lineStyle.equals("dash")) {
        fg.setLineDash(lineWeight * 4f, lineWeight);
    } else {
        fg.setLineDash(0);
    }

    //fg.setLineWidth(5);
    fg.setColorStroke(new BaseColor(c.getRGB()));
    fg.setColorFill(new BaseColor(c.getRGB()));
    float[] prefl = scaleShape(pointsSt, masterHeight, masterWidth, pageNum);
    float[] fl = sketchTrans(prefl, pageNum);

    /* Addition. ftorres - 7/22/2015 - Added to account for rotated pages 
     *   with the origin (0,0) not set to the bottom-left of the page. [1400] */
    float flTrans[] = translateRotation(fl[0], fl[1], pageNum);

    if (points.indexOf("LINEPOINT") != -1) {
        fg.circle(flTrans[0], flTrans[1], 5);
        fg.fillStroke();
        if (t == -1) {
            gs1.setFillOpacity(0f);
        } else {
            gs1.setFillOpacity(f);
        }
        fg.setGState(gs1);
    }
    fg.moveTo(flTrans[0], flTrans[1]);
    for (int i = 2; i < pointsSt.length; i = i + 2) {
        flTrans = translateRotation(fl[i], fl[i + 1], pageNum);
        fg.lineTo(flTrans[0], flTrans[1]);
    }

    if (t != -1) {
        fg.closePathFillStroke();
        fg.fill();
    } else {
        fg.stroke();
    }

    return "";
}

From source file:EplanPrinter.PDFPrint.java

License:Open Source License

public String insertComment(String sx, String sy, String id, String deptValue, String userInit, String comment,
        int pageNum, int masterHeight, int masterWidth, int pinned, int customFontSize)
        throws DocumentException, IOException {
    float ratio = getRatio(masterHeight, masterWidth, pageNum);
    float x = Float.parseFloat(sx);
    float y = Float.parseFloat(sy);
    float[] f = commentTrans(x, y, masterHeight, masterWidth, pageNum);
    PdfGState gs1 = new PdfGState();
    gs1.setFillOpacity(1);//  www. java 2  s  .c  o  m
    if (customFontSize > 0)
        fontSize = customFontSize;

    PdfContentByte fg = pds.getOverContent(pageNum);
    fg.setGState(gs1);
    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
    float[] trans = translate(x, y, r[pageNum - 1].getHeight(), r[pageNum - 1].getWidth(), masterHeight,
            masterWidth, pageNum);
    // comment tag image (width=35pts, height=8pts)
    float[] scalar = scale(trans[0], trans[1], 35, 8, masterHeight, masterWidth, pageNum);

    /* Addition. ftorres - 7/21/2015 - Added to account for rotated pages 
     *   with the origin (0,0) not set to the bottom-left of the page. [1400] */
    float coords[] = translateRotation(trans[0], trans[1], pageNum);
    coords = checkBounds(coords[0], coords[1], pageNum);

    /* Addition. ftorres - 10/20/2015 - If the comment was pinned in EPC, then
     *   render the comment inside a comment box. */
    if (pinned == 1) {
        insertPinnedComment(coords[0], coords[1], id + " - " + deptValue + " (" + userInit + ")", comment,
                pageNum, masterHeight, masterWidth);

        // Add the pinned comment text to page annotation -Jon Changkachith 11/24/2015
        Rectangle rect = new Rectangle(0, 0, 0, 0);
        PdfAnnotation annotation = PdfAnnotation.createText(pds.getWriter(), rect,
                id + " - " + deptValue + " (" + userInit + ")", cleanupComment(comment), true, id);
        pds.addAnnotation(annotation, pds.getWriter().getCurrentPageNumber());
    } else {
        Image image = Image.getInstance(commentIMGPath);
        image.setAbsolutePosition(coords[0] + (scalar[0] * (id.length() / 5f)), coords[1]);

        /*
         * Commented out by Jon Changkachith 12/09/2015 because it was throwing
         * DocumentException with the message "The image must have absolute positioning."
        image.scaleAbsoluteHeight(1);
        image.scaleAbsoluteWidth(1);
        */
        image.scalePercent(ratio); //Added to fix DocumentException "The image must have absolute positioning." Jon Changkachith 12/09/2015
        image.setAnnotation(new Annotation(id + " - " + deptValue + " (" + userInit + ")",
                cleanupComment(comment), 0, 0, 0, 0));
        fg.addImage(image);
    }

    fg.setLineWidth(.5f * ratio);
    fg.setColorStroke(new BaseColor(Color.decode("0x6E2405").getRGB()));
    fg.setColorFill(new BaseColor(Color.decode("0x6E2405").getRGB()));

    float tHeight = scalar[1];
    float tWidth = 0;
    if (id.length() > 3) {
        tWidth = (scalar[0] * (id.length() / 5f));
    } else {
        tWidth = (scalar[0]);
    }

    fg.moveTo(coords[0], coords[1]);
    fg.lineTo(coords[0] + (10f * ratio), coords[1] - (tHeight / 2));
    fg.lineTo(coords[0] + tWidth, coords[1] - (tHeight / 2));
    fg.lineTo(coords[0] + tWidth, coords[1] + (tHeight / 2));
    fg.lineTo(coords[0] + (10f * ratio), coords[1] + (tHeight / 2));

    fg.lineTo(coords[0], coords[1]);
    fg.closePathFillStroke();
    fg.fill();

    // Comment number that goes on the comment tag image
    Phrase p = new Phrase(id);
    p.getFont().setColor(BaseColor.WHITE);
    p.getFont().setSize(8f * ratio); //comment number font size = 8f
    //p.getChunks().get(0).setAnnotation(PdfAnnotation.createText(pds.getWriter(), new Rectangle(trans[0],trans[1], trans[0]+5f, trans[1]+5f), id, comment, true, id));

    float fs[] = translateRotation(f[0], f[1], pageNum);
    fs = checkBounds(fs[0], fs[1], pageNum);
    ColumnText.showTextAligned(fg, Element.ALIGN_LEFT, p, (float) (fs[0] + (9 * ratio)),
            (float) (fs[1] - (3 * ratio)), 0);

    return "";
}

From source file:EplanPrinter.PDFPrint.java

License:Open Source License

private void insertPinnedComment(float xCoord, float yCoord, String id, String comment, int pageNum,
        int masterHeight, int masterWidth) throws DocumentException, IOException {

    int standardHeight = 38;
    int standardWidth = 130;
    int lineHeight = 7;

    if (fontSize == 8) {
        standardHeight = 48;/*from   w  w  w .  j av a 2s.c  om*/
        standardWidth = 180;
        lineHeight = 10;
    } else if (fontSize == 10) {
        standardHeight = 70;
        standardWidth = 210;
        lineHeight = 12;
    }

    // comment box position defines lower-left corner
    xCoord += 41; // x-coordinate of comment text box
    yCoord -= 7; // lower offset moves box up

    float f = (float) 0.4;
    PdfGState gs1 = new PdfGState();
    gs1.setFillOpacity(f);

    PdfContentByte fg = pds.getOverContent(pageNum);
    fg.setGState(gs1);
    fg.setLineWidth(.5f * getRatio(masterHeight, masterWidth, pageNum));

    // Calculate additional needed height for the comment, based on length of comment.
    List<String> lines = createComment(cleanupComment(comment));
    int numLines = lines.size();
    int commentHeight = (numLines - 1) * lineHeight;

    // Draw the comment box
    String color = "0xF2F3E4";
    Color c = Color.decode(color);
    color = "0xFAFAF4";
    Color c2 = Color.decode(color);
    fg.setLineWidth(1f);
    fg.setColorStroke(new BaseColor(c.getRGB()));
    fg.setColorFill(new BaseColor(c2.getRGB()));
    float newCoords[] = pinnedCoords(xCoord, yCoord, standardWidth, standardHeight + commentHeight);
    fg.roundRectangle(xCoord, newCoords[1], standardWidth, standardHeight + commentHeight, 2f);
    fg.fillStroke();

    //BaseFont bf = BaseFont.createFont();
    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, true);
    BaseFont bfb = BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, true);
    fg.setColorFill(BaseColor.RED);
    gs1.setFillOpacity(0.8f);
    fg.setGState(gs1);

    // Adding comment title text
    Phrase phrase = new Phrase("Comment", new Font(bfb, fontSize));
    ColumnText.showTextAligned(fg, Element.ALIGN_LEFT, phrase, xCoord + 3, yCoord - 7, 0);

    // Adding comment number
    phrase = new Phrase(id, new Font(bf, fontSize));
    float offset = xCoord + 35;
    if (fontSize == 8)
        offset = xCoord + 45;
    else if (fontSize == 10)
        offset = xCoord + 55;
    ColumnText.showTextAligned(fg, Element.ALIGN_LEFT, phrase, offset, yCoord - 7, 0);

    /*  Remove 10/27/2015 Jon Changkachith
    // Adding 'comment' label text
    phrase = new Phrase("Comment", new Font(bfb, fontSize));
    ColumnText.showTextAligned(fg, Element.ALIGN_LEFT, phrase, xCoord + 3, yCoord - 20f, 0);
    */

    // Adding comment text
    int commentYOffset = 32;
    for (int i = 0; i < lines.size(); i++) {
        //phrase = new Phrase(lines.get(i), new Font(bf, fontSize));
        phrase = composePhrase(lines.get(i), bf, bfb);
        ColumnText.showTextAligned(fg, Element.ALIGN_LEFT, phrase, xCoord + 3, yCoord - commentYOffset, 0);
        commentYOffset += lineHeight;
    }

}

From source file:fenix.planner.pdf.PDFGenerator.java

License:Open Source License

private static BaseColor awtColorToBaseColor(Color awtColor) {
    return new BaseColor(awtColor.getRGB());
}