com.itextpdf.text.Document

Here are the examples of the java api com.itextpdf.text.Document taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

150 Examples 7

19 Source : PageHeaderFooterEvent.java
with Apache License 2.0
from youseries

@Override
public void onEndPage(PdfWriter writer, Doreplacedent doreplacedent) {
    List<Page> pages = report.getPages();
    int pageNumber = writer.getPageNumber();
    if (pageNumber > pages.size()) {
        return;
    }
    Page page = pages.get(pageNumber - 1);
    HeaderFooter header = page.getHeader();
    HeaderFooter footer = page.getFooter();
    if (header != null) {
        buildTable(writer, header, true, report);
    }
    if (footer != null) {
        buildTable(writer, footer, false, report);
    }
}

19 Source : PDFUtil.java
with Apache License 2.0
from ylxseu

// iText allows to add metadata to the PDF which can be viewed in your Adobe
// Reader
// under File -> Properties
private void addMetaData(Doreplacedent doreplacedent) {
    doreplacedent.addreplacedle("My first PDF");
    doreplacedent.addSubject("Using iText");
    doreplacedent.addKeywords("Java, PDF, iText");
    doreplacedent.addAuthor("Lars Vogel");
    doreplacedent.addCreator("Lars Vogel");
}

19 Source : ChartExportUtil.java
with GNU General Public License v2.0
from mzmine

/**
 * This method saves a chart as a PDF with given dimensions
 *
 * @param chart
 * @param width
 * @param height
 * @param fileName is a full path
 */
public static void writeChartToPDF(JFreeChart chart, int width, int height, File fileName) throws Exception {
    PdfWriter writer = null;
    Doreplacedent doreplacedent = new Doreplacedent(new Rectangle(width, height));
    try {
        writer = PdfWriter.getInstance(doreplacedent, new FileOutputStream(fileName));
        doreplacedent.open();
        PdfContentByte contentByte = writer.getDirectContent();
        PdfTemplate template = contentByte.createTemplate(width, height);
        Graphics2D graphics2d = template.createGraphics(width, height, new DefaultFontMapper());
        Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, width, height);
        chart.draw(graphics2d, rectangle2d);
        graphics2d.dispose();
        contentByte.addTemplate(template, 0, 0);
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    } finally {
        doreplacedent.close();
    }
}

19 Source : PdfReportPageNumber.java
with Apache License 2.0
from muxiangqiu

/**
 * Fills out the total number of pages before the doreplacedent is closed.
 * @see com.itextpdf.text.pdf.PdfPageEventHelper#onCloseDoreplacedent(
 *      com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Doreplacedent)
 */
public void onCloseDoreplacedent(PdfWriter writer, Doreplacedent doreplacedent) {
    ColumnText.showTextAligned(total, Element.ALIGN_LEFT, new Phrase(String.valueOf(writer.getPageNumber() - 1)), 2, 2, 0);
}

19 Source : PdfReportPageNumber.java
with Apache License 2.0
from muxiangqiu

/**
 * Creates the PdfTemplate that will hold the total number of pages.
 * @see com.itextpdf.text.pdf.PdfPageEventHelper#onOpenDoreplacedent(
 *      com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Doreplacedent)
 */
public void onOpenDoreplacedent(PdfWriter writer, Doreplacedent doreplacedent) {
    total = writer.getDirectContent().createTemplate(22, 16);
    total.setColorFill(new BaseColor(55, 55, 55));
}

19 Source : PdfReportBuilder.java
with Apache License 2.0
from muxiangqiu

public void addNewline(Doreplacedent doc, int i) throws DoreplacedentException {
    if (i > 0) {
        for (int j = 0; j < i; j++) {
            doc.add(Chunk.NEWLINE);
        }
    }
}

19 Source : FortuneXMLWorkerHelper.java
with Apache License 2.0
from landy8530

/**
 * Parses the xml data. This method configures the XMLWorker to parse
 * (X)HTML/CSS and accept unknown tags. Writes the output in the given
 * PdfWriter with the given doreplacedent.
 *
 * @param writer the PdfWriter
 * @param doc    the Doreplacedent
 * @param in     the reader
 * @throws IOException thrown when something went wrong with the IO
 */
public void parseXHtml(final PdfWriter writer, final Doreplacedent doc, final Reader in) throws IOException {
    CssFilesImpl cssFiles = new CssFilesImpl();
    cssFiles.add(getDefaultCSS());
    StyleAttrCSSResolver cssResolver = new StyleAttrCSSResolver(cssFiles);
    HtmlPipelineContext hpc = new HtmlPipelineContext(getCssAppliers());
    hpc.setAcceptUnknown(true).autoBookmark(true).setTagFactory(getDefaultTagProcessorFactory());
    Pipeline<?> pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(hpc, new PdfWriterPipeline(doc, writer)));
    XMLWorker worker = new XMLWorker(pipeline, true);
    XMLParser p = new XMLParser();
    p.addListener(worker);
    p.parse(in);
}

19 Source : FortuneXMLWorkerHelper.java
with Apache License 2.0
from landy8530

public void parseXHtml(final PdfWriter writer, final Doreplacedent doc, final InputStream in, final InputStream inCssFile, final Charset charset) throws IOException {
    parseXHtml(writer, doc, in, inCssFile, charset, new XMLWorkerFontProvider());
}

19 Source : FortuneXMLWorkerHelper.java
with Apache License 2.0
from landy8530

public void parseXHtml(final PdfWriter writer, final Doreplacedent doc, final InputStream in, final InputStream inCssFile, final FontProvider fontProvider) throws IOException {
    parseXHtml(writer, doc, in, inCssFile, null, fontProvider);
}

19 Source : FortuneXMLWorkerHelper.java
with Apache License 2.0
from landy8530

/**
 * @param writer  the writer to use
 * @param doc     the doreplacedent to use
 * @param in      the {@link InputStream} of the XHTML source.
 * @param in      the {@link CssFiles} of the css files.
 * @param charset the charset to use
 * @throws IOException if the {@link InputStream} could not be read.
 */
public void parseXHtml(final PdfWriter writer, final Doreplacedent doc, final InputStream in, final InputStream inCssFile, final Charset charset, final FontProvider fontProvider) throws IOException {
    CssFilesImpl cssFiles = new CssFilesImpl();
    if (inCssFile != null)
        cssFiles.add(getCSS(inCssFile));
    else
        cssFiles.add(getDefaultCSS());
    StyleAttrCSSResolver cssResolver = new StyleAttrCSSResolver(cssFiles);
    HtmlPipelineContext hpc = new HtmlPipelineContext(getCssAppliers());
    hpc.setAcceptUnknown(true).autoBookmark(true).setTagFactory(getDefaultTagProcessorFactory());
    HtmlPipeline htmlPipeline = new HtmlPipeline(hpc, new PdfWriterPipeline(doc, writer));
    Pipeline<?> pipeline = new CssResolverPipeline(cssResolver, htmlPipeline);
    XMLWorker worker = new XMLWorker(pipeline, true);
    XMLParser p = new XMLParser(true, worker, charset);
    if (charset != null)
        p.parse(in, charset);
    else
        p.parse(in);
}

19 Source : FortuneXMLWorkerHelper.java
with Apache License 2.0
from landy8530

/**
 * @param writer the writer to use
 * @param doc    the doreplacedent to use
 * @param in     the {@link InputStream} of the XHTML source.
 * @throws IOException if the {@link InputStream} could not be read.
 */
public void parseXHtml(final PdfWriter writer, final Doreplacedent doc, final InputStream in) throws IOException {
    parseXHtml(writer, doc, in, XMLWorkerHelper.clreplaced.getResourcereplacedtream("/default.css"), null, new XMLWorkerFontProvider());
}

19 Source : FortuneXMLWorkerHelper.java
with Apache License 2.0
from landy8530

public void parseXHtml(final PdfWriter writer, final Doreplacedent doc, final InputStream in, final InputStream inCssFile) throws IOException {
    parseXHtml(writer, doc, in, inCssFile, null, new XMLWorkerFontProvider());
}

19 Source : FortuneXMLWorkerHelper.java
with Apache License 2.0
from landy8530

/**
 * @param writer  the writer to use
 * @param doc     the doreplacedent to use
 * @param in      the {@link InputStream} of the XHTML source.
 * @param charset the charset to use
 * @throws IOException if the {@link InputStream} could not be read.
 */
public void parseXHtml(final PdfWriter writer, final Doreplacedent doc, final InputStream in, final Charset charset) throws IOException {
    parseXHtml(writer, doc, in, XMLWorkerHelper.clreplaced.getResourcereplacedtream("/default.css"), charset);
}

19 Source : TableKeepTogether.java
with GNU Affero General Public License v3.0
from haoxiaoyong1014

private void printPage3(Doreplacedent doreplacedent, PdfContentByte canvas) throws DoreplacedentException {
    int cols = 3;
    int rows = 15;
    PdfPTable table = new PdfPTable(cols);
    for (int row = 0; row < rows; row++) {
        for (int col = 0; col < cols; col++) {
            table.addCell(new Phrase("Cell " + row + ", " + col));
        }
    }
    table.setSpacingBefore(5);
    Rectangle docBounds = doreplacedent.getPageSize();
    Rectangle upper = new Rectangle(docBounds.getLeft(20), docBounds.getTop(20) - 200, docBounds.getRight(20), docBounds.getTop(20));
    upper.setBackgroundColor(new BaseColor(23, 142, 255, 20));
    Rectangle lower = new Rectangle(docBounds.getLeft(20), docBounds.getBottom(20), docBounds.getRight(20), docBounds.getBottom(20) + 600);
    lower.setBackgroundColor(new BaseColor(255, 142, 23, 20));
    Rectangle[] rectangles = new Rectangle[] { upper, lower };
    for (Rectangle bounds : rectangles) {
        bounds.setBorder(Rectangle.BOX);
        bounds.setBorderColor(BaseColor.BLACK);
        bounds.setBorderWidth(1);
        canvas.rectangle(bounds);
    }
    rectangles = drawKeepTogether(new Paragraph("This table should keep together!"), canvas, rectangles);
    rectangles = drawKeepTogether(table, canvas, rectangles);
}

19 Source : PdfExportTest.java
with GNU General Public License v3.0
from Bin-mario

private void getInfo(Doreplacedent doreplacedent) throws DoreplacedentException {
    NormalContent content = new NormalContent(12, false);
    content.setAlignment(Element.ALIGN_RIGHT);
    Map<Object, Object> info = new HashMap<Object, Object>();
    info.put("作者", "Hello World");
    info.put("更新时间", "2016-09-21 10:17:05");
    content.addContent(info);
    content.add(Chunk.NEXTPAGE);
    doreplacedent.add(content);
}

19 Source : PdfExportTest.java
with GNU General Public License v3.0
from Bin-mario

private void putData(Doreplacedent doreplacedent) throws DoreplacedentException {
    getRootTile(doreplacedent);
    getInfo(doreplacedent);
    getChapter1(doreplacedent);
    getChapter2(doreplacedent);
}

19 Source : PdfExportTest.java
with GNU General Public License v3.0
from Bin-mario

private void getRootTile(Doreplacedent doreplacedent) throws DoreplacedentException {
    Rootreplacedle replacedle = new Rootreplacedle(doreplacedent, "小幺鸡使用说明");
    doreplacedent.add(replacedle);
}

19 Source : PdfExportTest.java
with GNU General Public License v3.0
from Bin-mario

private void getChapter2(Doreplacedent doreplacedent) throws DoreplacedentException {
    Normalreplacedle replacedle = new Normalreplacedle("JSON测试", 2);
    NormalSubreplacedle replacedle1 = new NormalSubreplacedle(replacedle, "对象数组", 1);
    NormalSubreplacedle replacedle2 = new NormalSubreplacedle(replacedle1, "基本信息", 1, 10);
    replacedle2.getFont().setSize(12F);
    NormalContent content = new NormalContent();
    Map<String, String> data = new LinkedHashMap<String, String>();
    data.put("请求类型", "HTTP");
    data.put("接口地址", "http://www.xiaoyaoji.com.cn/test/json/3.json");
    data.put("请求方式", "GET");
    data.put("数据类型", "X-WWW-FORM-URLENCODED");
    data.put("响应类型", "JSON");
    data.put("接口状态", "启用");
    content.addContent(data);
    replacedle2.add(content);
    NormalSubreplacedle replacedle3 = new NormalSubreplacedle(replacedle1, "响应数据", 2, 10);
    replacedle3.getFont().setSize(12F);
    NormalContent content3 = new NormalContent();
    List<List<Object>> table = new ArrayList<List<Object>>();
    Object[] header = new Object[] { "参数名称", "是否必须", "数据类型", "描述" };
    Object[] param1 = new Object[] { "menu", "true", "object", "" };
    Object[] param2 = new Object[] { "menu.header", "true", "string", "" };
    Object[] param3 = new Object[] { "items.header", "true", "array[object]", "" };
    Object[] param4 = new Object[] { "items.id", "true", "string", "" };
    Object[] param5 = new Object[] { "items.label", "true", "string", "" };
    table.add(Arrays.asList(header));
    table.add(Arrays.asList(param1));
    table.add(Arrays.asList(param2));
    table.add(Arrays.asList(param3));
    table.add(Arrays.asList(param4));
    table.add(Arrays.asList(param5));
    content3.addTable(table);
    replacedle3.add(content3);
    doreplacedent.add(replacedle);
}

19 Source : PdfExportPlugin.java
with GNU General Public License v3.0
from Bin-mario

private static void printDoc(int order, Object parent, Doc doc, Object[] globalParams, Doreplacedent doreplacedent) throws DoreplacedentException {
    boolean isFolder = false;
    Element replacedle = null;
    switch(DocType.parse(doc.getType())) {
        case SYS_FOLDER:
            replacedle = printFolder(order, parent, doc);
            isFolder = true;
            break;
        case SYS_HTTP:
            replacedle = printHttp(order, parent, doc, globalParams);
            break;
        case SYS_DOC_RICH_TEXT:
            replacedle = printRichText(order, parent, doc);
            break;
        case SYS_DOC_MD:
            replacedle = printMd(order, parent, doc);
            break;
        case SYS_WEBSOCKET:
            replacedle = printWebsocket(order, parent, doc);
            break;
        case SYS_THIRDPARTY:
            replacedle = printThirdpart(order, parent, doc);
            break;
    }
    if (isFolder) {
        List<Doc> children = doc.getChildren();
        for (int i = 0; i < children.size(); i++) {
            printDoc(i, replacedle, children.get(i), globalParams, doreplacedent);
        }
    }
    if (parent == null) {
        doreplacedent.add(replacedle);
    }
}

19 Source : PdfExportPlugin.java
with GNU General Public License v3.0
from Bin-mario

private static void printRootreplacedle(Project project, Doreplacedent doreplacedent) throws DoreplacedentException {
    Rootreplacedle replacedle = new Rootreplacedle(doreplacedent, project.getName());
    doreplacedent.add(replacedle);
}

19 Source : PdfExportPlugin.java
with GNU General Public License v3.0
from Bin-mario

private static void printProjectInfo(Project project, Doreplacedent doreplacedent) throws DoreplacedentException {
    NormalContent desc = new NormalContent(12, false);
    desc.addContent(project.getDescription());
    doreplacedent.add(desc);
    NormalContent content = new NormalContent(12, false);
    content.setAlignment(Element.ALIGN_RIGHT);
    Map<Object, Object> info = new HashMap<Object, Object>();
    info.put("作者", ServiceFactory.instance().getUserName(project.getUserId()));
    info.put("更新时间", new SimpleDateFormat("yyyy-MM-dd").format(project.getLastUpdateTime()));
    content.addContent(info);
    // content.add(Chunk.NEXTPAGE);
    doreplacedent.add(content);
}

19 Source : PdfExportPlugin.java
with GNU General Public License v3.0
from Bin-mario

private static void printChapters(Project project, Doreplacedent doreplacedent) throws DoreplacedentException {
    List<Doc> docs = ProjectService.instance().getProjectDocs(project.getId(), true);
    ProjectGlobal global = ProjectService.instance().getProjectGlobal(project.getId());
    Object[] result = printGlobleParam(0, global, doreplacedent);
    int order = (int) result[0];
    order = printEnvironment(order, global, doreplacedent);
    for (int i = 0; i < docs.size(); i++) {
        printDoc(i + order, null, docs.get(i), result, doreplacedent);
    }
}

18 Source : PDFUtil.java
with Apache License 2.0
from ylxseu

public void createPDF() {
    // create doreplacedent object
    Doreplacedent doreplacedent = new Doreplacedent();
    // output file path
    try {
        PdfWriter.getInstance(doreplacedent, new FileOutputStream(outpath));
        doreplacedent.open();
        addMetaData(doreplacedent);
        addContent(doreplacedent);
        doreplacedent.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (DoreplacedentException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

18 Source : FileService.java
with Apache License 2.0
from SAP

private boolean addContentMetadata(File existingFile, InputStream stream) {
    // reset data in case of updates to existing files
    existingFile.setPageCount(0);
    existingFile.setDuration(0);
    existingFile.setWidth(0);
    existingFile.setHeight(0);
    existingFile.setVersion(null);
    existingFile.setDescription(null);
    existingFile.setParameters(null);
    existingFile.setScreenshotPath(null);
    existingFile.setErrorState(null);
    existingFile = FileDAO.save(existingFile);
    switch(existingFile.getFileType()) {
        case "pdf":
            try (PDDoreplacedent doc = PDDoreplacedent.load(stream)) {
                existingFile.setPageCount(doc.getNumberOfPages());
            } catch (InvalidPreplacedwordException e) {
                logger.error("Invalid preplacedword.", e);
                return false;
            } catch (IOException e) {
                logger.error("IO exception.", e);
                return false;
            }
            break;
        case "jpg":
        case "png":
        case "gif":
        case "ico":
        case "svg":
        case "bmp":
            try {
                BufferedImage bimg = ImageIO.read(stream);
                existingFile.setWidth(bimg.getWidth());
                existingFile.setHeight(bimg.getHeight());
            } catch (IOException e) {
                logger.error("IO exception.", e);
                return false;
            }
            break;
        case "mp4":
            try (FFmpegFrameGrabber g = new FFmpegFrameGrabber(stream);
                ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
                g.start();
                existingFile.setDuration(Math.toIntExact(g.getLengthInTime() / 1000000));
                existingFile.setWidth(g.getImageWidth());
                existingFile.setHeight(g.getImageHeight());
                g.stop();
            } catch (IOException e) {
                logger.error("IO exception.", e);
            }
            break;
        case "pptx":
            // convert to pdf
            XMLSlideShow ppt;
            try {
                ppt = new XMLSlideShow(stream);
            } catch (IOException e) {
                logger.error("IO exception.", e);
                return false;
            }
            // getting the dimensions and size of the slide, scale to improve quality
            Dimension pgsize = ppt.getPageSize();
            float scale = 2;
            int width = (int) (pgsize.width * scale);
            int height = (int) (pgsize.height * scale);
            List<XSLFSlide> slide = ppt.getSlides();
            BufferedImage img = null;
            Doreplacedent doc = new Doreplacedent();
            try (ByteArrayOutputStream pdfBos = new ByteArrayOutputStream()) {
                PdfWriter.getInstance(doc, pdfBos);
                doc.open();
                for (int i = 0; i < slide.size(); i++) {
                    // prepare
                    img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
                    Graphics2D graphics = img.createGraphics();
                    graphics.setPaint(Color.white);
                    graphics.fill(new Rectangle2D.Float(0, 0, width, height));
                    graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                    graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
                    graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
                    graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
                    graphics.scale(scale, scale);
                    // render
                    slide.get(i).draw(graphics);
                    ByteArrayOutputStream pageBos = new ByteArrayOutputStream();
                    ImageIO.write(img, "png", pageBos);
                    ppt.write(pageBos);
                    // convert
                    Image image = Image.getInstance(pageBos.toByteArray());
                    doc.setPageSize(new Rectangle(image.getScaledWidth(), image.getScaledHeight()));
                    doc.newPage();
                    image.setAbsolutePosition(0, 0);
                    doc.add(image);
                    pageBos.close();
                }
                doc.close();
                // save new pdf file, delete original
                String fileKey = FilenameUtils.getBaseName(existingFile.getFileKey()) + ".pdf";
                byte[] pdfBytes = pdfBos.toByteArray();
                getECM().deleteDoreplacedentByName(existingFile.getFileKey(), true);
                getECM().uploadDoreplacedent(fileKey, pdfBytes, mimeTypes.get("pdf"));
                existingFile.setDateModified(new Date());
                existingFile.setSize(pdfBytes.length);
                existingFile.setFileKey(fileKey);
                existingFile.setFileType("pdf");
                return addContentMetadata(existingFile, new ByteArrayInputStream(pdfBytes));
            } catch (Exception e) {
                logger.error("Conversion exception.", e);
                return false;
            }
        case "template":
            parseTemplate(existingFile, stream);
            break;
    }
    existingFile = FileDAO.save(existingFile);
    return true;
}

18 Source : PersionPDFUtil.java
with GNU Lesser General Public License v2.1
from newtouch-cloud

/**
 * 传入参数导出PDF,并把信息存入数据库
 */
@SuppressWarnings("null")
public static ByteArrayOutputStream fillEmployee(IPersonManageVOModel baseInfo) {
    Doreplacedent doc = new Doreplacedent();
    try {
        BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        Font textfont = new Font(bfChinese, 13, Font.NORMAL);
        Font keyfont = new Font(bfChinese, 13, Font.BOLD);
        Font headfont = new Font(bfChinese, 13, Font.BOLD);
    } catch (Exception e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    // 模板路径
    // 设置时间格式
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
    // 获得当前时间
    String createdate = sdf.format(new Date());
    String templatePath = PathFactory.getSource() + "/WEB-INF/pdf/保险代理从业人员执业登记注册表.pdf";
    // String newPDFPath = "E:/保险代理从业人员执业登记注册表" + createdate + ".pdf";
    PdfReader reader;
    FileOutputStream out;
    ByteArrayOutputStream bos = null;
    PdfStamper stamper;
    try {
        // out = new FileOutputStream(newPDFPath);// 输出流
        // 读取pdf模板
        reader = new PdfReader(templatePath);
        // 可以捕获内存缓存中的数据,转换成字节数组。
        bos = new ByteArrayOutputStream();
        stamper = new PdfStamper(reader, bos);
        AcroFields form = stamper.getAcroFields();
        java.util.Iterator<String> it = form.getFields().keySet().iterator();
        // BaseInfo baseInfo = info.getEmployeeBody().getBaseInfo();
        // 姓名
        form.setField("Text1", baseInfo.getPerson_name());
        if ("1".equals(baseInfo.getSex())) {
            // 性别
            form.setField("Text2", "男");
        }
        if ("2".equals(baseInfo.getSex())) {
            // 性别
            form.setField("Text2", "女");
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd ");
        // 出生年月
        form.setField("Text3", DateUtil.getStringDateMonth(baseInfo.getBirthday()));
        // 民族
        form.setField("Text4", baseInfo.getNational());
        // 文化程度
        form.setField("Text5", baseInfo.getEducation());
        // --政治面貌
        form.setField("Text6", baseInfo.getPolitical());
        // 身份证号
        form.setField("Text7", baseInfo.getIdcard());
        // 毕业学校
        form.setField("Text8", baseInfo.getSchool());
        // --固定电话
        form.setField("Text9", baseInfo.getTel());
        // 移动电话
        form.setField("Text10", baseInfo.getPhone());
        // --户籍地址
        form.setField("Text11", baseInfo.getIdcard_adress());
        // 乡镇
        form.setField("Text12", "");
        // --现地址
        form.setField("Text13", baseInfo.getHome_address());
        // 执业区域
        form.setField("Text14", baseInfo.getPractice_area());
        // 公司工号
        form.setField("Text15", baseInfo.getPerson_no());
        // 所属机构
        form.setField("Text16", baseInfo.getBranch_name());
        // --用工合同类型
        form.setField("Text17", baseInfo.getContract_type());
        // 业务范围
        form.setField("Text18", baseInfo.getBusiness_scope());
        // 申请人签字
        form.setField("Text19", "");
        // 签字年月日
        form.setField("Text20", DateUtil.getStringDateMonth(DateUtil.sysDate()));
        // 未逾5年 有
        form.setField("Text21", "");
        // 未逾5年 无
        form.setField("Text22", "√");
        // 未逾3年 有
        form.setField("Text23", "");
        // 未逾3年 无
        form.setField("Text24", "√");
        // 未届满 有
        form.setField("Text25", "");
        // 未届满 无
        form.setField("Text26", "√");
        // 申请人签字
        form.setField("Text27", "");
        // 经办人签字
        form.setField("Text28", "");
        // 签字年月日
        form.setField("Text29", DateUtil.getStringDateMonth(DateUtil.sysDate()));
        Image image = Image.getInstance(PathFactory.getSource() + "/WEB-INF/pdf/1522806114831.jpg");
        float doreplacedentWidth = doc.getPageSize().getWidth() - doc.leftMargin() - doc.rightMargin();
        // 重新设置宽高
        float doreplacedentHeight = doreplacedentWidth / 580 * 320;
        // 重新设置宽高
        image.scaleAbsolute(100, 200);
        PushbuttonField pushbuttonField = form.getNewPushbuttonFromField("image");
        pushbuttonField.setImage(image);
        PdfFormField editFormField = pushbuttonField.getField();
        form.replacePushbuttonField("image", editFormField);
        // 如果为false那么生成的PDF文件还能编辑,一定要设为true
        stamper.setFormFlattening(true);
        stamper.close();
        // PdfCopy copy = new PdfCopy(doc, out);
        doc.open();
        // PdfImportedPage importPage = copy.getImportedPage(new
        // PdfReader(bos.toByteArray()), 1);
        // copy.addPage(importPage);
        doc.close();
    } catch (IOException e) {
        System.out.println(1);
    } catch (DoreplacedentException e) {
        System.out.println(2);
    }
    return bos;
}

18 Source : PersionPDFUtil.java
with GNU Lesser General Public License v2.1
from newtouch-cloud

// 利用模板生成pdf
public static ByteArrayOutputStream fillOperation(IPersonManageVOModel baseInfo, List<IEducationVOModel> educationInfos, List<IEducationVOModel> workInfos) {
    Doreplacedent doc = new Doreplacedent();
    // BaseInfo baseInfo = info.getEmployeeBody().getBaseInfo();
    try {
        BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        Font textfont = new Font(bfChinese, 10, Font.NORMAL);
    } catch (DoreplacedentException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    // 模板路径
    String templatePath = PathFactory.getSource() + "/WEB-INF/pdf/保险中介从业人员基本情况登记表.pdf";
    // 生成的新文件路径
    // 设置时间格式
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
    // 获得当前时间
    String createdate = sdf.format(new Date());
    // String newPDFPath = "E:/保险中介从业人员基本情况登记表" + createdate + ".pdf";
    PdfReader reader;
    FileOutputStream out;
    ByteArrayOutputStream bos = null;
    PdfStamper stamper;
    try {
        // out = new FileOutputStream(newPDFPath);// 输出流
        // 读取pdf模板
        reader = new PdfReader(templatePath);
        // 可以捕获内存缓存中的数据,转换成字节数组。
        bos = new ByteArrayOutputStream();
        stamper = new PdfStamper(reader, bos);
        AcroFields form = stamper.getAcroFields();
        java.util.Iterator<String> it = form.getFields().keySet().iterator();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd ");
        // 姓名
        form.setField("Text1", baseInfo.getPerson_name());
        if ("1".equals(baseInfo.getSex())) {
            // 性别
            form.setField("Text2", "男");
        }
        if ("2".equals(baseInfo.getSex())) {
            // 性别
            form.setField("Text2", "女");
        }
        // 民族
        form.setField("Text3", baseInfo.getNational());
        // 出生年月
        form.setField("Text4", DateUtil.getStringDateMonth(baseInfo.getBirthday()));
        // 学历
        form.setField("Text5", baseInfo.getEducation());
        // 政治面貌
        form.setField("Text6", baseInfo.getPolitical());
        // 身份证号
        form.setField("Text7", baseInfo.getIdcard());
        // 移动电话
        form.setField("Text8", baseInfo.getPhone());
        // --固定电话
        form.setField("Text9", baseInfo.getTel());
        // --户口所在地
        form.setField("Text10", baseInfo.getIdcard_adress());
        // 专业技术资格
        form.setField("Text11", baseInfo.getTechnology_no());
        // --婚否
        form.setField("Text12", "");
        // --家庭住址
        form.setField("Text13", baseInfo.getHome_address());
        // --兼职情况
        String contract_type = baseInfo.getContract_type();
        /*if ("1".equals(contract_type)) {
				form.setField("Text14", "√");// --兼职情况 专职
			} else {
				form.setField("Text15", "√");// 兼职情况 兼职
			}*/
        // List<EducationInfo> educationInfos =
        // info.getEmployeeBody().getEducationInfos();
        /*for (int i = 1; i < educationInfos.size() + 1; i++) {
				int j = 6 * i + 10;
				IEducationVOModel educationInfo = educationInfos.get(i - 1);
				// 学历教育情况列表 (学历教育集合)
				form.setField("Text" + Integer.toString(j++), format.format(educationInfo.getStart_date()));// 入学年月
				form.setField("Text" + Integer.toString(j++), format.format(educationInfo.getGraduation_date()));// 毕业年月
				form.setField("Text" + Integer.toString(j++), educationInfo.getAddress());// 毕业学校
				form.setField("Text" + Integer.toString(j++), educationInfo.getMajor());// 专业
				form.setField("Text" + Integer.toString(j++), educationInfo.getYear());// 学制
				form.setField("Text" + Integer.toString(j++), educationInfo.getDegree());// 学历
			}*/
        // List<WorkInfo> workInfos = info.getEmployeeBody().getWorkInfos();
        /*for (int i = 1; i < workInfos.size() + 1; i++) {
				int j = 5 * i + 35;
				IEducationVOModel educationInfo = workInfos.get(i - 1);
				// 个人从业经历列表(从业经历集合)1
				form.setField("Text" + Integer.toString(j++), format.format(educationInfo.getStart_date()));// 起始日期
				form.setField("Text" + Integer.toString(j++), format.format(educationInfo.getGraduation_date()));// 终止日期
				form.setField("Text" + Integer.toString(j++), educationInfo.getAddress());// 在何地,何单位从事何工作
				form.setField("Text" + Integer.toString(j++), educationInfo.getWork_position());// 职务
				form.setField("Text" + Integer.toString(j++), educationInfo.getApprove_person());// 证明人
			}*/
        Image image = Image.getInstance(PathFactory.getSource() + "/WEB-INF/pdf/1522806114831.jpg");
        float doreplacedentWidth = doc.getPageSize().getWidth() - doc.leftMargin() - doc.rightMargin();
        // 重新设置宽高
        float doreplacedentHeight = doreplacedentWidth / 580 * 320;
        // 重新设置宽高
        image.scaleAbsolute(100, 200);
        PushbuttonField pushbuttonField = form.getNewPushbuttonFromField("image");
        pushbuttonField.setImage(image);
        PdfFormField editFormField = pushbuttonField.getField();
        form.replacePushbuttonField("image", editFormField);
        // 如果为false那么生成的PDF文件还能编辑,一定要设为true
        stamper.setFormFlattening(true);
        stamper.close();
        doc.open();
        // PdfCopy copy = new PdfCopy(doc, out);
        // PdfImportedPage importPage = copy.getImportedPage(new
        // PdfReader(bos.toByteArray()), 1);
        // copy.addPage(importPage);
        doc.close();
    } catch (IOException e) {
        System.out.println(e);
    } catch (DoreplacedentException e) {
        System.out.println(e);
    }
    return bos;
}

18 Source : SwingExportUtil.java
with GNU General Public License v2.0
from mzmine

/**
 * Writes swing to pdf
 *
 * @param panel
 * @param fileName
 * @throws DoreplacedentException
 * @throws Exception
 */
public static void writeToPDF(JComponent panel, File fileName) throws IOException, DoreplacedentException {
    // print the panel to pdf
    int width = panel.getWidth();
    int height = panel.getHeight();
    logger.info(() -> MessageFormat.format("Exporting panel to PDF file (width x height; {0} x {1}): {2}", width, height, fileName.getAbsolutePath()));
    Doreplacedent doreplacedent = new Doreplacedent(new Rectangle(width, height));
    PdfWriter writer = null;
    try {
        writer = PdfWriter.getInstance(doreplacedent, new FileOutputStream(fileName));
        doreplacedent.open();
        PdfContentByte contentByte = writer.getDirectContent();
        PdfTemplate template = contentByte.createTemplate(width, height);
        Graphics2D g2 = new PdfGraphics2D(contentByte, width, height, new DefaultFontMapper());
        panel.print(g2);
        g2.dispose();
        contentByte.addTemplate(template, 0, 0);
        doreplacedent.close();
        writer.close();
    } finally {
        if (doreplacedent.isOpen()) {
            doreplacedent.close();
        }
    }
}

18 Source : PdfReportBuilder.java
with Apache License 2.0
from muxiangqiu

public void addGridToDoreplacedent(Doreplacedent doc, Reportreplacedle reportreplacedle, ReportDataModel reportDataModel) throws Exception {
    doc.add(createGridTable(reportDataModel, reportreplacedle.isRepeatHeader()));
}

18 Source : ReportFooter.java
with Apache License 2.0
from muratartim

@Override
public void onEndPage(PdfWriter writer, Doreplacedent doreplacedent) {
    // do not add on first page
    if (doreplacedent.getPageNumber() == 1)
        return;
    // get canvas
    PdfContentByte canvas = writer.getDirectContent();
    // create top rectangle
    Rectangle topRectangle = new Rectangle(0, doreplacedent.top() + 10, doreplacedent.right() + doreplacedent.rightMargin(), doreplacedent.top() + doreplacedent.topMargin());
    topRectangle.setBackgroundColor(new BaseColor(70, 130, 180));
    canvas.rectangle(topRectangle);
    // create bottom rectangle
    Rectangle bottomRectangle = new Rectangle(0, 0, doreplacedent.right() + doreplacedent.rightMargin(), doreplacedent.bottom() - 20);
    bottomRectangle.setBackgroundColor(new BaseColor(70, 130, 180));
    canvas.rectangle(bottomRectangle);
    // write top-right footer (creation date)
    Phrase topRight = new Phrase("Date: " + date_, font_);
    ColumnText.showTextAligned(canvas, Element.ALIGN_RIGHT, topRight, doreplacedent.right(), doreplacedent.top() + 20, 0);
    // write top-left footer (replacedle)
    Phrase topLeft = new Phrase(replacedle_, font_);
    ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, topLeft, doreplacedent.left(), doreplacedent.top() + 20, 0);
    // write bottom-right footer (page number)
    Phrase bottomRight = new Phrase("Page " + doreplacedent.getPageNumber(), font_);
    ColumnText.showTextAligned(canvas, Element.ALIGN_RIGHT, bottomRight, doreplacedent.right(), doreplacedent.bottom() - 40, 0);
    // write bottom-left footer (Equinox version)
    Phrase bottomLeft = new Phrase("Generated by Equinox version " + Equinox.VERSION.toString(), font_);
    ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, bottomLeft, doreplacedent.left(), doreplacedent.bottom() - 40, 0);
}

18 Source : PdfExportServer.java
with Apache License 2.0
from jueyue

/**
 * PDF导出服务,基于Excel基础的导出
 * @author JueYue
 *  2015年10月6日 下午8:21:08
 */
public clreplaced PdfExportServer extends ExportCommonService {

    private static final Logger LOGGER = LoggerFactory.getLogger(PdfExportServer.clreplaced);

    private Doreplacedent doreplacedent;

    private IPdfExportStyler styler;

    private boolean isListData = false;

    public PdfExportServer(OutputStream outStream, PdfExportParams enreplacedy) {
        try {
            styler = enreplacedy.getStyler() == null ? new PdfExportStylerDefaultImpl() : enreplacedy.getStyler();
            doreplacedent = styler.getDoreplacedent();
            PdfWriter.getInstance(doreplacedent, outStream);
            doreplacedent.open();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
    }

    /**
     * 创建Pdf的表格数据
     * @param enreplacedy
     * @param pojoClreplaced
     * @param dataSet
     * @return
     */
    public Doreplacedent createPdf(PdfExportParams enreplacedy, Clreplaced<?> pojoClreplaced, Collection<?> dataSet) {
        try {
            List<ExcelExportEnreplacedy> excelParams = new ArrayList<ExcelExportEnreplacedy>();
            if (enreplacedy.isAddIndex()) {
            // excelParams.add(indexExcelEnreplacedy(enreplacedy));
            }
            // 得到所有字段
            Field[] fileds = PoiPublicUtil.getClreplacedFields(pojoClreplaced);
            ExcelTarget etarget = pojoClreplaced.getAnnotation(ExcelTarget.clreplaced);
            String targetId = etarget == null ? null : etarget.value();
            getAllExcelField(enreplacedy.getExclusions(), targetId, fileds, excelParams, pojoClreplaced, null, null);
            createPdfByExportEnreplacedy(enreplacedy, excelParams, dataSet);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        } finally {
            try {
                doreplacedent.close();
            } catch (Exception e) {
            // 可能之前已经关闭过了
            }
        }
        return doreplacedent;
    }

    public Doreplacedent createPdfByExportEnreplacedy(PdfExportParams enreplacedy, List<ExcelExportEnreplacedy> excelParams, Collection<?> dataSet) {
        try {
            sortAllParams(excelParams);
            for (int k = 0, paramSize = excelParams.size(); k < paramSize; k++) {
                if (excelParams.get(k).getList() != null) {
                    isListData = true;
                    break;
                }
            }
            // 设置各个列的宽度
            float[] widths = getCellWidths(excelParams);
            PdfPTable table = new PdfPTable(widths.length);
            table.setTotalWidth(widths);
            // table.setLockedWidth(true);
            // 设置表头
            createHeaderAndreplacedle(enreplacedy, table, excelParams);
            int rowHeight = getRowHeight(excelParams) / 50;
            Iterator<?> its = dataSet.iterator();
            while (its.hasNext()) {
                Object t = its.next();
                createCells(table, t, excelParams, rowHeight);
            }
            doreplacedent.add(table);
        } catch (DoreplacedentException e) {
            LOGGER.error(e.getMessage(), e);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        } finally {
            doreplacedent.close();
        }
        return doreplacedent;
    }

    private void createCells(PdfPTable table, Object t, List<ExcelExportEnreplacedy> excelParams, int rowHeight) throws Exception {
        ExcelExportEnreplacedy enreplacedy;
        int maxHeight = getThisMaxHeight(t, excelParams);
        for (int k = 0, paramSize = excelParams.size(); k < paramSize; k++) {
            enreplacedy = excelParams.get(k);
            if (enreplacedy.getList() != null) {
                Collection<?> list = getListCellValue(enreplacedy, t);
                for (Object obj : list) {
                    createListCells(table, obj, enreplacedy.getList(), rowHeight);
                }
            } else {
                Object value = getCellValue(enreplacedy, t);
                if (enreplacedy.getType() == 1) {
                    createStringCell(table, value == null ? "" : value.toString(), enreplacedy, rowHeight, 1, maxHeight);
                } else {
                    createImageCell(table, value == null ? "" : value.toString(), enreplacedy, rowHeight, 1, maxHeight);
                }
            }
        }
    }

    /**
     * 创建集合对象
     * @param table
     * @param obj
     * @param rowHeight
     * @param excelParams
     * @throws Exception
     */
    private void createListCells(PdfPTable table, Object obj, List<ExcelExportEnreplacedy> excelParams, int rowHeight) throws Exception {
        ExcelExportEnreplacedy enreplacedy;
        for (int k = 0, paramSize = excelParams.size(); k < paramSize; k++) {
            enreplacedy = excelParams.get(k);
            Object value = getCellValue(enreplacedy, obj);
            if (enreplacedy.getType() == 1) {
                createStringCell(table, value == null ? "" : value.toString(), enreplacedy, rowHeight);
            } else {
                createImageCell(table, value == null ? "" : value.toString(), enreplacedy, rowHeight, 1, 1);
            }
        }
    }

    /**
     * 获取这一列的高度
     * @param t             对象
     * @param excelParams   属性列表
     * @return
     * @throws Exception    通过反射过去值得异常
     */
    private int getThisMaxHeight(Object t, List<ExcelExportEnreplacedy> excelParams) throws Exception {
        if (isListData) {
            ExcelExportEnreplacedy enreplacedy;
            int maxHeight = 1;
            for (int k = 0, paramSize = excelParams.size(); k < paramSize; k++) {
                enreplacedy = excelParams.get(k);
                if (enreplacedy.getList() != null) {
                    Collection<?> list = getListCellValue(enreplacedy, t);
                    maxHeight = (list == null || maxHeight > list.size()) ? maxHeight : list.size();
                }
            }
            return maxHeight;
        }
        return 1;
    }

    /**
     * 获取Cells的宽度数组
     * @param excelParams
     * @return
     */
    private float[] getCellWidths(List<ExcelExportEnreplacedy> excelParams) {
        List<Float> widths = new ArrayList<Float>();
        for (int i = 0; i < excelParams.size(); i++) {
            if (excelParams.get(i).getList() != null) {
                List<ExcelExportEnreplacedy> list = excelParams.get(i).getList();
                for (int j = 0; j < list.size(); j++) {
                    widths.add((float) (20 * list.get(j).getWidth()));
                }
            } else {
                widths.add((float) (20 * excelParams.get(i).getWidth()));
            }
        }
        float[] widthArr = new float[widths.size()];
        for (int i = 0; i < widthArr.length; i++) {
            widthArr[i] = widths.get(i);
        }
        return widthArr;
    }

    private void createHeaderAndreplacedle(PdfExportParams enreplacedy, PdfPTable table, List<ExcelExportEnreplacedy> excelParams) throws DoreplacedentException {
        int feildWidth = getFieldLength(excelParams);
        if (enreplacedy.getreplacedle() != null) {
            createHeaderRow(enreplacedy, table, feildWidth);
        }
        createreplacedleRow(enreplacedy, table, excelParams);
    }

    /**
     * 创建表头
     *
     * @param replacedle
     * @param table
     */
    private int createreplacedleRow(PdfExportParams replacedle, PdfPTable table, List<ExcelExportEnreplacedy> excelParams) {
        int rows = getRowNums(excelParams, false);
        for (int i = 0, exportFieldreplacedleSize = excelParams.size(); i < exportFieldreplacedleSize; i++) {
            ExcelExportEnreplacedy enreplacedy = excelParams.get(i);
            if (enreplacedy.getList() != null) {
                if (StringUtils.isNotBlank(enreplacedy.getName())) {
                    createStringCell(table, enreplacedy.getName(), enreplacedy, 10, enreplacedy.getList().size(), 1);
                }
                List<ExcelExportEnreplacedy> sreplacedel = enreplacedy.getList();
                for (int j = 0, size = sreplacedel.size(); j < size; j++) {
                    createStringCell(table, sreplacedel.get(j).getName(), sreplacedel.get(j), 10);
                }
            } else {
                createStringCell(table, enreplacedy.getName(), enreplacedy, 10, 1, rows == 2 ? 2 : 1);
            }
        }
        return rows;
    }

    private void createHeaderRow(PdfExportParams enreplacedy, PdfPTable table, int feildLength) {
        PdfPCell iCell = new PdfPCell(new Phrase(enreplacedy.getreplacedle(), styler.getFont(null, enreplacedy.getreplacedle())));
        iCell.setHorizontalAlignment(Element.ALIGN_CENTER);
        iCell.setVerticalAlignment(Element.ALIGN_CENTER);
        iCell.setFixedHeight(enreplacedy.getreplacedleHeight());
        iCell.setColspan(feildLength + 1);
        table.addCell(iCell);
        if (enreplacedy.getSecondreplacedle() != null) {
            iCell = new PdfPCell(new Phrase(enreplacedy.getSecondreplacedle(), styler.getFont(null, enreplacedy.getSecondreplacedle())));
            iCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
            iCell.setVerticalAlignment(Element.ALIGN_CENTER);
            iCell.setFixedHeight(enreplacedy.getSecondreplacedleHeight());
            iCell.setColspan(feildLength + 1);
            table.addCell(iCell);
        }
    }

    private PdfPCell createStringCell(PdfPTable table, String text, ExcelExportEnreplacedy enreplacedy, int rowHeight, int colspan, int rowspan) {
        PdfPCell iCell = new PdfPCell(new Phrase(text, styler.getFont(enreplacedy, text)));
        styler.setCellStyler(iCell, enreplacedy, text);
        iCell.setFixedHeight((int) (rowHeight * 2.5));
        if (colspan > 1) {
            iCell.setColspan(colspan);
        }
        if (rowspan > 1) {
            iCell.setRowspan(rowspan);
        }
        table.addCell(iCell);
        return iCell;
    }

    private PdfPCell createStringCell(PdfPTable table, String text, ExcelExportEnreplacedy enreplacedy, int rowHeight) {
        PdfPCell iCell = new PdfPCell(new Phrase(text, styler.getFont(enreplacedy, text)));
        styler.setCellStyler(iCell, enreplacedy, text);
        iCell.setFixedHeight((int) (rowHeight * 2.5));
        table.addCell(iCell);
        return iCell;
    }

    private PdfPCell createImageCell(PdfPTable table, String text, ExcelExportEnreplacedy enreplacedy, int rowHeight, int rowSpan, int colSpan) {
        try {
            Image image = Image.getInstance(ImageCache.getImage(text));
            PdfPCell iCell = new PdfPCell(image);
            styler.setCellStyler(iCell, enreplacedy, text);
            iCell.setFixedHeight((int) (rowHeight * 2.5));
            table.addCell(iCell);
            return iCell;
        } catch (BadElementException e) {
            LOGGER.error(e.getMessage(), e);
        } catch (MalformedURLException e) {
            LOGGER.error(e.getMessage(), e);
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }
        return new PdfPCell();
    }
}

18 Source : UnifiedPagesizeMerging.java
with GNU Affero General Public License v3.0
from haoxiaoyong1014

/**
 * <a href="http://stackoverflow.com/questions/28945802/get-pdf-be-written-in-the-center-of-the-page-itextsharp">
 * Get PDF be written in the center of the page itextsharp
 * </a>
 * <p>
 * A Java solution...
 * </p>
 */
@Test
public void testMerge() throws IOException, DoreplacedentException {
    try (InputStream testA4Stream = getClreplaced().getResourcereplacedtream("testA4.pdf");
        InputStream fromStream = getClreplaced().getResourcereplacedtream("from.pdf");
        InputStream prefaceStream = getClreplaced().getResourcereplacedtream("preface.pdf");
        InputStream type3Stream = getClreplaced().getResourcereplacedtream("Test_Type3_Problem.pdf")) {
        final List<PdfReader> readers = new ArrayList<PdfReader>(Arrays.asList(new PdfReader(testA4Stream), new PdfReader(fromStream), new PdfReader(prefaceStream), new PdfReader(type3Stream)));
        for (int run = 0; run < readers.size(); run++) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            Doreplacedent doreplacedent = new Doreplacedent();
            PdfCopy copy = new PdfCopy(doreplacedent, baos);
            doreplacedent.open();
            for (PdfReader reader : readers) {
                copy.addDoreplacedent(reader);
            }
            doreplacedent.close();
            File target = new File(RESULT_FOLDER, String.format("unified-pagesize-%s.pdf", run));
            FileOutputStream output = new FileOutputStream(target);
            PdfReader reader = new PdfReader(baos.toByteArray());
            Rectangle unifiedSize = reader.getCropBox(1);
            unifiedSize.setRotation(reader.getPageRotation(1));
            float width, height;
            if (unifiedSize.getRotation() % 180 == 0) {
                width = unifiedSize.getWidth();
                height = unifiedSize.getHeight();
            } else {
                height = unifiedSize.getWidth();
                width = unifiedSize.getHeight();
            }
            for (int pageNumber = 1; pageNumber <= reader.getNumberOfPages(); pageNumber++) {
                Rectangle centeredCrop = centerIn(reader.getCropBox(pageNumber), reader.getPageRotation(pageNumber), width, height);
                Rectangle enhancedMedia = enhanceBy(reader.getPageSize(pageNumber), centeredCrop);
                reader.getPageN(pageNumber).put(PdfName.CROPBOX, new PdfRectangle(centeredCrop));
                reader.getPageN(pageNumber).put(PdfName.MEDIABOX, new PdfRectangle(enhancedMedia));
            }
            PdfStamper stamper = new PdfStamper(reader, output);
            stamper.close();
            readers.add(readers.remove(0));
        }
    }
}

18 Source : CreateAndAppendDoc.java
with GNU Affero General Public License v3.0
from haoxiaoyong1014

/**
 * <a href="http://stackoverflow.com/questions/29001852/how-to-create-a-pdf-and-you-then-merge-another-pdf-to-the-same-doreplacedent-using-it">
 * how to create a PDF and you then merge another pdf to the same doreplacedent using itext
 * </a>
 * <p>
 * Testing the OP's method with <code>paginate</code> set to <code>true</code>
 * </p>
 */
@Test
public void testAppendPDFsPaginate() throws IOException, DoreplacedentException {
    try (InputStream testA4Stream = getClreplaced().getResourcereplacedtream("testA4.pdf");
        InputStream fromStream = getClreplaced().getResourcereplacedtream("from.pdf");
        InputStream prefaceStream = getClreplaced().getResourcereplacedtream("preface.pdf");
        InputStream type3Stream = getClreplaced().getResourcereplacedtream("Test_Type3_Problem.pdf");
        FileOutputStream output = new FileOutputStream(new File(RESULT_FOLDER, "appendPdfsPaginate.pdf"))) {
        Doreplacedent doreplacedent = new Doreplacedent();
        PdfWriter writer = PdfWriter.getInstance(doreplacedent, output);
        doreplacedent.open();
        doreplacedent.add(new Paragraph("Some content to start with"));
        appendPDFs(Arrays.asList(testA4Stream, fromStream, prefaceStream, type3Stream), writer, doreplacedent, null, true);
        doreplacedent.close();
    }
}

18 Source : CreateAndAppendDoc.java
with GNU Affero General Public License v3.0
from haoxiaoyong1014

/**
 * <a href="http://stackoverflow.com/questions/29001852/how-to-create-a-pdf-and-you-then-merge-another-pdf-to-the-same-doreplacedent-using-it">
 * how to create a PDF and you then merge another pdf to the same doreplacedent using itext
 * </a>
 * <p>
 * Testing the OP's method with <code>paginate</code> set to <code>false</code>
 * </p>
 */
@Test
public void testAppendPDFs() throws IOException, DoreplacedentException {
    try (InputStream testA4Stream = getClreplaced().getResourcereplacedtream("testA4.pdf");
        InputStream fromStream = getClreplaced().getResourcereplacedtream("from.pdf");
        InputStream prefaceStream = getClreplaced().getResourcereplacedtream("preface.pdf");
        InputStream type3Stream = getClreplaced().getResourcereplacedtream("Test_Type3_Problem.pdf");
        FileOutputStream output = new FileOutputStream(new File(RESULT_FOLDER, "appendPdfs.pdf"))) {
        Doreplacedent doreplacedent = new Doreplacedent();
        PdfWriter writer = PdfWriter.getInstance(doreplacedent, output);
        doreplacedent.open();
        doreplacedent.add(new Paragraph("Some content to start with"));
        appendPDFs(Arrays.asList(testA4Stream, fromStream, prefaceStream, type3Stream), writer, doreplacedent, null, false);
        doreplacedent.close();
    }
}

18 Source : StampHeader.java
with GNU Affero General Public License v3.0
from haoxiaoyong1014

/**
 * <a href="http://stackoverflow.com/questions/29977927/table-header-in-pdf-getting-displayed-using-itextpdf5-1-1-but-not-in-itextpdf5-5">
 * table header in pdf getting displayed using itextpdf5.1.1 but not in itextpdf5.5.3
 * </a>
 * <p>
 * Indeed, the code as presented by the OP does not show the header table. This makes sense, though:
 * </p>
 * <p>
 * The OP has cells with default padding (i.e. 2) and height 10, and he tries to insert text at height 7.
 * But 2 (top margin) + 7 (text height) + 2 (bottom margin) = 11, i.e. more than fits into the cell height 10.
 * Thus, the text does not fit and is not displayed.
 * </p>
 * <p>
 * You can fix this by either
 * <ul>
 * <li>using a smaller font, e.g. 6, or
 * <li>using a higher cell, e.g. 11, or
 * <li>using a smaller padding, e.g. 1, see below-
 * </p>
 */
@Test
public void testSandeepSinghHeaderTable() throws DoreplacedentException, IOException {
    byte[] strIntermediatePDFFile = createSampleDoreplacedent();
    String header1 = "Header 1";
    String header2 = "Header 2";
    String header3 = "Header 3";
    String header5 = "Header 5";
    Doreplacedent doreplacedent = new Doreplacedent(PageSize.A4.rotate(), 20, 20, 75, 20);
    PdfCopy copy = new PdfCopy(doreplacedent, new FileOutputStream(new File(RESULT_FOLDER, "stampTableHeader.pdf")));
    doreplacedent.open();
    PdfReader pdfReaderIntermediate = new PdfReader(strIntermediatePDFFile);
    int numberOfPages = pdfReaderIntermediate.getNumberOfPages();
    Font ffont = new Font(Font.FontFamily.UNDEFINED, 7, Font.NORMAL);
    System.out.println("###### No. of Pages: " + numberOfPages);
    for (int j = 0; j < numberOfPages; ) {
        PdfImportedPage page = copy.getImportedPage(pdfReaderIntermediate, ++j);
        PageStamp stamp = copy.createPageStamp(page);
        Phrase footer = new Phrase(String.format("%d of %d", j, numberOfPages), ffont);
        ColumnText.showTextAligned(stamp.getUnderContent(), Element.ALIGN_CENTER, footer, (doreplacedent.right() - doreplacedent.left()) / 2 + doreplacedent.leftMargin(), doreplacedent.bottom() - 10, 0);
        if (j != 1) {
            PdfPTable headerTable = new PdfPTable(2);
            headerTable.setTotalWidth(700);
            headerTable.getDefaultCell().setFixedHeight(10);
            headerTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
            // Added!
            headerTable.getDefaultCell().setPadding(1);
            headerTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
            headerTable.addCell(new Phrase(String.format(header1), ffont));
            headerTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
            headerTable.addCell(new Phrase(String.format(header2), ffont));
            headerTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
            headerTable.addCell(new Phrase(String.format(header3), ffont));
            headerTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
            headerTable.addCell(new Phrase(String.format(header5, j), ffont));
            headerTable.completeRow();
            headerTable.writeSelectedRows(0, 5, 60.5f, 550, stamp.getUnderContent());
        }
        stamp.alterContents();
        copy.addPage(page);
    }
    doreplacedent.close();
}

18 Source : TableKeepTogether.java
with GNU Affero General Public License v3.0
from haoxiaoyong1014

private void printPage2(Doreplacedent doreplacedent, PdfContentByte canvas) throws DoreplacedentException {
    int cols = 3;
    int rows = 15;
    PdfPTable table = new PdfPTable(cols);
    for (int row = 0; row < rows; row++) {
        for (int col = 0; col < cols; col++) {
            table.addCell(new Phrase("Cell " + row + ", " + col));
        }
    }
    PdfPTable tableWrapper = new PdfPTable(1);
    tableWrapper.addCell(table);
    tableWrapper.setSplitRows(false);
    Paragraph paragraph = new Paragraph();
    paragraph.add(tableWrapper);
    ColumnText columnText = new ColumnText(canvas);
    columnText.addElement(new Paragraph("This table should keep together!"));
    columnText.addElement(tableWrapper);
    int status = ColumnText.START_COLUMN;
    Rectangle docBounds = doreplacedent.getPageSize();
    Rectangle bounds = new Rectangle(docBounds.getLeft(20), docBounds.getTop(20) - 200, docBounds.getRight(20), docBounds.getTop(20));
    bounds.setBorder(Rectangle.BOX);
    bounds.setBorderColor(BaseColor.BLACK);
    bounds.setBorderWidth(1);
    bounds.setBackgroundColor(new BaseColor(23, 142, 255, 20));
    canvas.rectangle(bounds);
    columnText.setSimpleColumn(bounds);
    status = columnText.go();
    if (ColumnText.hasMoreText(status)) {
        bounds = new Rectangle(docBounds.getLeft(20), docBounds.getBottom(20), docBounds.getRight(20), docBounds.getBottom(20) + 600);
        bounds.setBorder(Rectangle.BOX);
        bounds.setBorderColor(BaseColor.BLACK);
        bounds.setBorderWidth(1);
        bounds.setBackgroundColor(new BaseColor(255, 142, 23, 20));
        canvas.rectangle(bounds);
        columnText.setSimpleColumn(bounds);
        status = columnText.go();
    }
}

18 Source : TableKeepTogether.java
with GNU Affero General Public License v3.0
from haoxiaoyong1014

private void printPage1(Doreplacedent doreplacedent, PdfContentByte canvas) throws DoreplacedentException {
    int cols = 3;
    int rows = 15;
    PdfPTable table = new PdfPTable(cols);
    for (int row = 0; row < rows; row++) {
        for (int col = 0; col < cols; col++) {
            table.addCell(new Phrase("Cell " + row + ", " + col));
        }
    }
    Paragraph paragraph = new Paragraph();
    paragraph.add(table);
    ColumnText columnText = new ColumnText(canvas);
    columnText.addElement(new Paragraph("This table should keep together!"));
    columnText.addElement(table);
    int status = ColumnText.START_COLUMN;
    Rectangle docBounds = doreplacedent.getPageSize();
    Rectangle bounds = new Rectangle(docBounds.getLeft(20), docBounds.getTop(20) - 200, docBounds.getRight(20), docBounds.getTop(20));
    bounds.setBorder(Rectangle.BOX);
    bounds.setBorderColor(BaseColor.BLACK);
    bounds.setBorderWidth(1);
    bounds.setBackgroundColor(new BaseColor(23, 142, 255, 20));
    canvas.rectangle(bounds);
    columnText.setSimpleColumn(bounds);
    status = columnText.go();
    if (ColumnText.hasMoreText(status)) {
        bounds = new Rectangle(docBounds.getLeft(20), docBounds.getBottom(20), docBounds.getRight(20), docBounds.getBottom(20) + 600);
        bounds.setBorder(Rectangle.BOX);
        bounds.setBorderColor(BaseColor.BLACK);
        bounds.setBorderWidth(1);
        bounds.setBackgroundColor(new BaseColor(255, 142, 23, 20));
        canvas.rectangle(bounds);
        columnText.setSimpleColumn(bounds);
        status = columnText.go();
    }
}

18 Source : CreateTableDirectContent.java
with GNU Affero General Public License v3.0
from haoxiaoyong1014

/**
 * <a href="http://stackoverflow.com/questions/43807931/creating-table-in-pdf-on-last-page-bottom-wrong-official-solution">
 * Creating table in pdf on last page bottom (wrong official solution)
 * </a>
 * <p>
 * Helper method for {@link #testCreateTableLikeUser7968180()}. Here the error
 * is corrected.
 * </p>
 */
private static void drawTableAtTheEndOfPage(Doreplacedent doreplacedent, PdfWriter writer, PdfPTable datatable) {
    datatable.setTotalWidth(doreplacedent.right() - doreplacedent.left());
    // datatable.setTotalWidth(doreplacedent.right(doreplacedent.rightMargin()) - doreplacedent.left(doreplacedent.leftMargin()));
    datatable.writeSelectedRows(0, -1, doreplacedent.left(), datatable.getTotalHeight() + doreplacedent.bottom(), writer.getDirectContent());
// datatable.writeSelectedRows(0, -1, doreplacedent.left(doreplacedent.leftMargin()),
// datatable.getTotalHeight() + doreplacedent.bottom(doreplacedent.bottomMargin()), writer.getDirectContent());
}

18 Source : ParagraphBackground.java
with GNU Affero General Public License v3.0
from haoxiaoyong1014

@Override
public void onStartPage(PdfWriter writer, Doreplacedent doreplacedent) {
    startPosition = doreplacedent.top();
}

18 Source : ParagraphBackground.java
with GNU Affero General Public License v3.0
from haoxiaoyong1014

@Override
public void onParagraph(PdfWriter writer, Doreplacedent doreplacedent, float paragraphPosition) {
    this.startPosition = paragraphPosition;
}

18 Source : Abstract2DPdfPageSplittingTool.java
with GNU Affero General Public License v3.0
from haoxiaoyong1014

/**
 * <a href="https://stackoverflow.com/questions/46466747/how-to-split-a-pdf-page-in-java">
 * How to split a PDF page in java?
 * </a>
 * <p>
 * This abstract utility clreplaced splits each source page into multiple
 * pages each representing one of a custom set of page sub areas.
 * </p>
 *
 * @author mkl
 */
public abstract clreplaced Abstract2DPdfPageSplittingTool {

    public void split(OutputStream outputStream, PdfReader... inputs) throws DoreplacedentException, IOException {
        try {
            initDoreplacedent(outputStream);
            for (PdfReader reader : inputs) {
                split(reader);
            }
        } finally {
            closeDoreplacedent();
        }
    }

    void initDoreplacedent(OutputStream outputStream) throws DoreplacedentException {
        final Doreplacedent doreplacedent = new Doreplacedent(PageSize.A4);
        final PdfWriter writer = PdfWriter.getInstance(doreplacedent, outputStream);
        this.doreplacedent = doreplacedent;
        this.writer = writer;
    }

    void closeDoreplacedent() {
        try {
            doreplacedent.close();
        } finally {
            this.doreplacedent = null;
            this.writer = null;
        }
    }

    void newPage(Rectangle pageSize) {
        doreplacedent.setPageSize(pageSize);
        if (!doreplacedent.isOpen())
            doreplacedent.open();
        else
            doreplacedent.newPage();
    }

    void split(PdfReader reader) throws IOException {
        for (int page = 1; page <= reader.getNumberOfPages(); page++) {
            split(reader, page);
        }
    }

    void split(PdfReader reader, int page) throws IOException {
        PdfImportedPage importedPage = writer.getImportedPage(reader, page);
        Rectangle pageSizeToImport = reader.getPageSize(page);
        Iterable<Rectangle> rectangles = determineSplitRectangles(reader, page);
        for (Rectangle rectangle : rectangles) {
            newPage(rectangle);
            PdfContentByte directContent = writer.getDirectContent();
            directContent.saveState();
            directContent.rectangle(rectangle.getLeft(), rectangle.getBottom(), rectangle.getWidth(), rectangle.getHeight());
            directContent.clip();
            directContent.newPath();
            writer.getDirectContent().addTemplate(importedPage, -pageSizeToImport.getLeft(), -pageSizeToImport.getBottom());
            directContent.restoreState();
        }
    }

    protected abstract Iterable<Rectangle> determineSplitRectangles(PdfReader reader, int page);

    Doreplacedent doreplacedent = null;

    PdfWriter writer = null;
}

18 Source : Logo.java
with GNU General Public License v3.0
from drivenbyentropy

/**
 * Stores the logo in PDF format
 * @param width
 * @param height
 * @param fileName
 */
public void saveRAWAsPDF(int width, int height, String fileName) {
    ChartPanel logo = getRawLogoPanel();
    PdfWriter writer = null;
    Rectangle pagesize = new Rectangle(width, height);
    Doreplacedent doreplacedent = new Doreplacedent(pagesize);
    try {
        writer = PdfWriter.getInstance(doreplacedent, new FileOutputStream(fileName));
        doreplacedent.open();
        PdfContentByte contentByte = writer.getDirectContent();
        PdfTemplate template = contentByte.createTemplate(width, height);
        Graphics2D graphics2d = template.createGraphics(width, height, new DefaultFontMapper());
        Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, width, height);
        logo.getChart().draw(graphics2d, rectangle2d);
        graphics2d.dispose();
        contentByte.addTemplate(template, 0, 0);
    } catch (Exception e) {
        e.printStackTrace();
    }
    doreplacedent.close();
}

18 Source : Logo.java
with GNU General Public License v3.0
from drivenbyentropy

/**
 * Stores the logo in PDF format
 * @param width
 * @param height
 * @param fileName
 */
public void saveAsPDF(int width, int height, String fileName) {
    if (chart == null) {
        makeSequenceLogo();
    }
    PdfWriter writer = null;
    Rectangle pagesize = new Rectangle(width, height);
    Doreplacedent doreplacedent = new Doreplacedent(pagesize);
    try {
        writer = PdfWriter.getInstance(doreplacedent, new FileOutputStream(fileName));
        doreplacedent.open();
        PdfContentByte contentByte = writer.getDirectContent();
        PdfTemplate template = contentByte.createTemplate(width, height);
        Graphics2D graphics2d = template.createGraphics(width, height, new DefaultFontMapper());
        Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, width, height);
        chart.draw(graphics2d, rectangle2d);
        graphics2d.dispose();
        contentByte.addTemplate(template, 0, 0);
    } catch (Exception e) {
        e.printStackTrace();
    }
    doreplacedent.close();
}

18 Source : PdfTool.java
with Apache License 2.0
from caryyu

/**
 * Created by cary on 6/15/17.
 */
public clreplaced PdfTool {

    // 
    protected Doreplacedent doreplacedent;

    // 
    protected OutputStream os;

    public Doreplacedent getDoreplacedent() {
        if (doreplacedent == null) {
            doreplacedent = new Doreplacedent();
        }
        return doreplacedent;
    }
}

18 Source : PdfExportTest.java
with GNU General Public License v3.0
from Bin-mario

@Test
public void test() throws IOException, DoreplacedentException {
    Doreplacedent doreplacedent = new Doreplacedent();
    PdfWriter.getInstance(doreplacedent, new FileOutputStream(DEST));
    doreplacedent.open();
    putData(doreplacedent);
    doreplacedent.close();
}

18 Source : PdfExportTest.java
with GNU General Public License v3.0
from Bin-mario

private void getChapter1(Doreplacedent doreplacedent) throws DoreplacedentException {
    Normalreplacedle replacedle = new Normalreplacedle("文档说明", 1);
    NormalContent content = new NormalContent();
    List<String> data = new ArrayList<String>();
    data.add("支持http、websocket测试");
    data.add("支持json,xml,txt,jsonp等测试");
    data.add("支持form-data,x-www-form-urlencoded ,raw,binary 上传格式");
    data.add("支持rest地址,http://www.test.com/test/{id}.json 这样的地址会自动替换id");
    data.add("由于浏览器跨域访问限制,为了更好的体验服务,请下载安装扩展 https://chrome.google.com/webstore/detail/%E5%B0%8F%E5%B9%BA%E9%B8%A1/omohfhadnbkakganodaofplinheljnbd");
    data.add("如果在使用过程中发现界面排版错误,请切换至chrome最新版本浏览器。其他浏览器,其他浏览器正在适配中。");
    data.add("如果配置了地址前缀,则该模块下所有url访问时会自动带上前缀。");
    data.add("如果有任何建议或意见都可以在这儿留言 http://www.xiaoyaoji.com.cn/help.html");
    data.add("有任何bug 都可以在这儿提出来 http://git.oschina.net/zhoujingjie/apiManager/issues");
    data.add("支持markdown编辑器");
    data.add("支持mock");
    data.add("支持变量");
    content.addContent(data);
    // String html = "<code><br>    使用方式:$变量名$<br>    如:$host$ = <a href=\"http://www.xiaoyaoji.com.cn\">http://www.xiaoyaoji.com.cn</a><br>    则:$host$/test/url = <a href=\"http://www.xiaoyaoji.com.cn/test/url\">http://www.xiaoyaoji.com.cn/test/url</a><br></code>";
    String html = "<p><h1><ul><li>范德萨发、hello发送是的</li><li>2、markdown</li></ul><h5><ol><li>是否是一个正确的文档</li></ol></h5></h1></p><p><br></p>";
    content.addHtml(html);
    replacedle.add(content);
    doreplacedent.add(replacedle);
}

18 Source : PdfExportPlugin.java
with GNU General Public License v3.0
from Bin-mario

private static Object[] printGlobleParam(int order, ProjectGlobal global, Doreplacedent doreplacedent) throws DoreplacedentException {
    Object[] result = new Object[5];
    String params = global.getHttp();
    JSONObject json = JSONObject.parseObject(params);
    if (json == null || json.isEmpty()) {
        result[0] = order;
        return result;
    }
    Doc doc = new Doc();
    doc.setName("全局变量");
    Element replacedle = printFolder(order, null, doc);
    int index = 0;
    JSONArray requestHeaders = json.getJSONArray("requestHeaders");
    if (requestHeaders != null && !requestHeaders.isEmpty()) {
        List<List<Object>> table = genReqHeaders(null, requestHeaders);
        result[1] = table;
        if (table != null) {
            NormalSubreplacedle replacedle3 = null;
            if (replacedle instanceof Normalreplacedle) {
                replacedle3 = new NormalSubreplacedle((Normalreplacedle) replacedle, "全局请求头", ++index);
            } else if (replacedle instanceof NormalSubreplacedle) {
                replacedle3 = new NormalSubreplacedle((NormalSubreplacedle) replacedle, "全局请求头", ++index);
            }
            replacedle3.getFont().setSize(12F);
            NormalContent content3 = new NormalContent();
            content3.addTable(table);
            replacedle3.add(content3);
        }
    }
    JSONArray requestArgs = json.getJSONArray("requestArgs");
    if (requestArgs != null && !requestArgs.isEmpty()) {
        List<List<Object>> table = genReqArgs(null, requestArgs);
        result[2] = table;
        if (table != null) {
            NormalSubreplacedle replacedle3 = null;
            if (replacedle instanceof Normalreplacedle) {
                replacedle3 = new NormalSubreplacedle((Normalreplacedle) replacedle, "全局请求数据", ++index);
            } else if (replacedle instanceof NormalSubreplacedle) {
                replacedle3 = new NormalSubreplacedle((NormalSubreplacedle) replacedle, "全局请求数据", ++index);
            }
            replacedle3.getFont().setSize(12F);
            NormalContent content3 = new NormalContent();
            content3.addTable(table);
            replacedle3.add(content3);
        }
    }
    JSONArray responseHeaders = json.getJSONArray("responseHeaders");
    if (requestArgs != null && !requestArgs.isEmpty()) {
        List<List<Object>> table = genRspHeaders(null, responseHeaders);
        result[3] = table;
        if (table != null) {
            NormalSubreplacedle replacedle3 = null;
            if (replacedle instanceof Normalreplacedle) {
                replacedle3 = new NormalSubreplacedle((Normalreplacedle) replacedle, "全局响应头", ++index);
            } else if (replacedle instanceof NormalSubreplacedle) {
                replacedle3 = new NormalSubreplacedle((NormalSubreplacedle) replacedle, "全局响应头", ++index);
            }
            replacedle3.getFont().setSize(12F);
            NormalContent content3 = new NormalContent();
            content3.addTable(table);
            replacedle3.add(content3);
        }
    }
    JSONArray responseArgs = json.getJSONArray("responseArgs");
    if (requestArgs != null && !requestArgs.isEmpty()) {
        List<List<Object>> table = genRspArgs(null, responseArgs);
        result[4] = table;
        if (table != null) {
            NormalSubreplacedle replacedle3 = null;
            if (replacedle instanceof Normalreplacedle) {
                replacedle3 = new NormalSubreplacedle((Normalreplacedle) replacedle, "全局响应数据", ++index);
            } else if (replacedle instanceof NormalSubreplacedle) {
                replacedle3 = new NormalSubreplacedle((NormalSubreplacedle) replacedle, "全局响应数据", ++index);
            }
            replacedle3.getFont().setSize(12F);
            NormalContent content3 = new NormalContent();
            content3.addTable(table);
            replacedle3.add(content3);
        }
    }
    doreplacedent.add(replacedle);
    result[0] = ++order;
    return result;
}

18 Source : PdfExportPlugin.java
with GNU General Public License v3.0
from Bin-mario

@Override
public void doExport(String projectId, HttpServletResponse response) throws IOException {
    Project project = ProjectService.instance().getProject(projectId);
    replacedertUtils.notNull("pdf export error:project or output stream cannot be null.", project);
    Doreplacedent doreplacedent = new Doreplacedent();
    try {
        PdfWriter.getInstance(doreplacedent, response.getOutputStream());
        doreplacedent.open();
        printRootreplacedle(project, doreplacedent);
        printProjectInfo(project, doreplacedent);
        printChapters(project, doreplacedent);
        doreplacedent.close();
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
}

18 Source : Database.java
with GNU General Public License v3.0
from appteam-nith

private void createPdf() throws FileNotFoundException, DoreplacedentException {
    File docsFolder = new File(Environment.getExternalStorageDirectory() + "/Doreplacedents");
    if (!docsFolder.exists()) {
        docsFolder.mkdir();
        Log.i(TAG, "Created a new directory for PDF");
    }
    pdfFile = new File(docsFolder.getAbsolutePath(), "MyCV.pdf");
    OutputStream output = new FileOutputStream(pdfFile);
    Doreplacedent doreplacedent = new Doreplacedent();
    PdfWriter.getInstance(doreplacedent, output);
    doreplacedent.open();
    Font bold = new Font(Font.FontFamily.HELVETICA, 20, Font.BOLD);
    Font bold1 = new Font(Font.FontFamily.TIMES_ROMAN, 28, Font.BOLDITALIC);
    Font regular = new Font(Font.FontFamily.HELVETICA, 18, Font.ITALIC);
    doreplacedent.add(new Paragraph("CURRICULUM VITAE" + "\n\n", bold1));
    for (int i = 0; i < 12; i++) {
        doreplacedent.add(new Paragraph(head[i], bold));
        doreplacedent.add(new Paragraph(val[i] + "\n", regular));
    }
    doreplacedent.close();
    Toast.makeText(Database.this, "MyCV.pdf created in Doreplacedents.", Toast.LENGTH_SHORT).show();
    finish();
    ContactDetail.name = "";
    ContactDetail.branch = "";
    ContactDetail.email = "";
    ContactDetail.mobile = "";
    SkillDetail.skill = "";
    SkillDetail.interset = "";
    SkillDetail.achievments = "";
    QuestionDetail.q1 = "";
    QuestionDetail.q2 = "";
    QuestionDetail.q3 = "";
    QuestionDetail.q4 = "";
// previewPdf();
}

18 Source : PDFDataExporter.java
with GNU General Public License v3.0
from AndreAle94

/**
 * Created by andrea on 22/12/18.
 */
public clreplaced PDFDataExporter extends AbstractDataExporter {

    private final File mOutputFile;

    private final Doreplacedent mDoreplacedent;

    private final MoneyFormatter mMoneyFormatter;

    private boolean mShouldLoadPeople = false;

    private int mChapterCount = 0;

    public PDFDataExporter(Context context, File folder) throws IOException {
        super(context, folder);
        mOutputFile = new File(folder, getDefaultFileName(".pdf"));
        mMoneyFormatter = MoneyFormatter.getInstance();
        mDoreplacedent = new Doreplacedent(PageSize.A4);
        try {
            PdfWriter.getInstance(mDoreplacedent, new FileOutputStream(mOutputFile));
        } catch (DoreplacedentException e) {
            throw new IOException(e);
        }
        mDoreplacedent.addAuthor("MoneyWallet - Expense Manager");
        mDoreplacedent.open();
    }

    @Override
    public boolean isMultiWalletSupported() {
        return true;
    }

    @Override
    public String[] getColumns(boolean uniqueWallet, String[] optionalColumns) {
        List<String> contractColumns = new ArrayList<>();
        contractColumns.add(Constants.COLUMN_DATETIME);
        contractColumns.add(Constants.COLUMN_CATEGORY);
        contractColumns.add(Constants.COLUMN_MONEY);
        if (uniqueWallet) {
            contractColumns.add(Constants.COLUMN_WALLET);
        }
        contractColumns.add(Constants.COLUMN_DESCRIPTION);
        if (optionalColumns != null) {
            for (String column : optionalColumns) {
                switch(column) {
                    case COLUMN_EVENT:
                        contractColumns.add(Constants.COLUMN_EVENT);
                        break;
                    case COLUMN_PEOPLE:
                        contractColumns.add(Constants.COLUMN_PEOPLE);
                        mShouldLoadPeople = true;
                        break;
                    case COLUMN_PLACE:
                        contractColumns.add(Constants.COLUMN_PLACE);
                        break;
                    case COLUMN_NOTE:
                        contractColumns.add(Constants.COLUMN_NOTE);
                        break;
                }
            }
        }
        return contractColumns.toArray(new String[contractColumns.size()]);
    }

    @Override
    public boolean shouldLoadPeople() {
        return mShouldLoadPeople;
    }

    @Override
    public void exportData(Cursor cursor, String[] columns, Wallet... wallets) throws IOException {
        try {
            Chapter chapter = createChapter(wallets);
            chapter.add(createTable(cursor, columns));
            mDoreplacedent.add(chapter);
        } catch (DoreplacedentException e) {
            throw new IOException(e);
        }
    }

    private Chapter createChapter(Wallet... wallets) throws DoreplacedentException {
        StringBuilder chapterreplacedleBuilder = new StringBuilder();
        if (wallets != null && wallets.length > 0) {
            for (Wallet wallet : wallets) {
                if (chapterreplacedleBuilder.length() != 0) {
                    chapterreplacedleBuilder.append(", ");
                }
                chapterreplacedleBuilder.append(wallet.getName());
            }
        } else {
            chapterreplacedleBuilder.append(getContext().getString(R.string.hint_unknown));
        }
        Font font = FontFactory.getFont(FontFactory.HELVETICA, 16, Font.BOLDITALIC);
        Chunk chunk = new Chunk(chapterreplacedleBuilder.toString(), font);
        Paragraph paragraph = new Paragraph(chunk);
        paragraph.setSpacingAfter(30);
        return new Chapter(paragraph, ++mChapterCount);
    }

    private PdfPTable createTable(Cursor cursor, String[] columns) throws DoreplacedentException {
        PdfPTable table = createTable(columns);
        for (int i = 0; i < cursor.getCount(); i++) {
            // move the cursor to the fixed position
            cursor.moveToPosition(i);
            // for each line of the cursor, write a line in the sheet
            for (String column : columns) {
                String label = null;
                switch(column) {
                    case Constants.COLUMN_DATETIME:
                        label = cursor.getString(cursor.getColumnIndex(Contract.Transaction.DATE));
                        break;
                    case Constants.COLUMN_CATEGORY:
                        label = cursor.getString(cursor.getColumnIndex(Contract.Transaction.CATEGORY_NAME));
                        break;
                    case Constants.COLUMN_MONEY:
                        CurrencyUnit currencyUnit = CurrencyManager.getCurrency(cursor.getString(cursor.getColumnIndex(Contract.Transaction.WALLET_CURRENCY)));
                        long money = cursor.getLong(cursor.getColumnIndex(Contract.Transaction.MONEY));
                        int direction = cursor.getInt(cursor.getColumnIndex(Contract.Transaction.DIRECTION));
                        if (direction == Contract.Direction.EXPENSE) {
                            money *= -1;
                        }
                        label = mMoneyFormatter.getNotTintedString(currencyUnit, money);
                        break;
                    case Constants.COLUMN_WALLET:
                        label = cursor.getString(cursor.getColumnIndex(Contract.Transaction.WALLET_NAME));
                        break;
                    case Constants.COLUMN_DESCRIPTION:
                        label = cursor.getString(cursor.getColumnIndex(Contract.Transaction.DESCRIPTION));
                        break;
                    case Constants.COLUMN_EVENT:
                        label = cursor.getString(cursor.getColumnIndex(Contract.Transaction.EVENT_NAME));
                        break;
                    case Constants.COLUMN_PEOPLE:
                        List<Long> peopleIds = Contract.parseObjectIds(cursor.getString(cursor.getColumnIndex(Contract.Transaction.PEOPLE_IDS)));
                        if (peopleIds != null && !peopleIds.isEmpty()) {
                            StringBuilder builder = new StringBuilder();
                            for (Long personId : peopleIds) {
                                String name = getPersonName(personId);
                                if (!TextUtils.isEmpty(name)) {
                                    if (builder.length() > 0) {
                                        builder.append(", ");
                                    }
                                    builder.append(name);
                                }
                            }
                            label = builder.toString();
                        } else {
                            label = null;
                        }
                        break;
                    case Constants.COLUMN_PLACE:
                        label = cursor.getString(cursor.getColumnIndex(Contract.Transaction.PLACE_NAME));
                        break;
                    case Constants.COLUMN_NOTE:
                        label = cursor.getString(cursor.getColumnIndex(Contract.Transaction.NOTE));
                        break;
                }
                table.addCell(label);
            }
        }
        return table;
    }

    private PdfPTable createTable(String[] columns) throws DoreplacedentException {
        // create the table with a fixed number of columns
        PdfPTable table = new PdfPTable(columns.length);
        table.setWidthPercentage(100f);
        table.getDefaultCell().setBackgroundColor(BaseColor.YELLOW);
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
        // initialize the table creating the header line
        Context context = getContext();
        for (String column : columns) {
            String label = null;
            switch(column) {
                case Constants.COLUMN_DATETIME:
                    label = context.getString(R.string.hint_date);
                    break;
                case Constants.COLUMN_CATEGORY:
                    label = context.getString(R.string.hint_category);
                    break;
                case Constants.COLUMN_MONEY:
                    label = context.getString(R.string.hint_money);
                    break;
                case Constants.COLUMN_WALLET:
                    label = context.getString(R.string.hint_wallet);
                    break;
                case Constants.COLUMN_DESCRIPTION:
                    label = context.getString(R.string.hint_description);
                    break;
                case Constants.COLUMN_EVENT:
                    label = context.getString(R.string.hint_event);
                    break;
                case Constants.COLUMN_PEOPLE:
                    label = context.getString(R.string.hint_people);
                    break;
                case Constants.COLUMN_PLACE:
                    label = context.getString(R.string.hint_place);
                    break;
                case Constants.COLUMN_NOTE:
                    label = context.getString(R.string.hint_note);
                    break;
            }
            table.addCell(label);
        }
        table.getDefaultCell().setBackgroundColor(BaseColor.WHITE);
        return table;
    }

    @Override
    public void close() throws IOException {
        mDoreplacedent.close();
    }

    @Override
    public File getOutputFile() {
        return mOutputFile;
    }

    @Override
    public String getResultType() {
        return "application/pdf";
    }
}

17 Source : PDFUtil.java
with Apache License 2.0
from ylxseu

private void addContent(Doreplacedent doreplacedent) throws DoreplacedentException, IOException {
    // BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
    BaseFont bfChinese = BaseFont.createFont("/sdcard/" + "black.ttf", BaseFont.IDENreplacedY_H, BaseFont.NOT_EMBEDDED);
    Font FontChinese1 = new Font(bfChinese, 30, Font.NORMAL);
    Font FontChinese2 = new Font(bfChinese, 20, Font.NORMAL);
    Anchor anchor = new Anchor("太好了", FontChinese1);
    // Anchor anchor = new Anchor("aaaaaaa");
    anchor.setName("ccc");
    // Second parameter is the number of the chapter
    Chapter catPart = new Chapter(new Paragraph(anchor), 1);
    Paragraph subPara = new Paragraph("终于可以显示中文了", FontChinese2);
    // Paragraph subPara = new Paragraph("replaced");
    Section subCatPart = catPart.addSection(subPara);
    subCatPart.add(new Paragraph("HP lazerJet 1020"));
    // add a list
    createList(subCatPart);
    Paragraph paragraph = new Paragraph();
    addEmptyLine(paragraph, 5);
    subCatPart.add(paragraph);
    // add a table
    createTable(subCatPart);
    // now add all this to the doreplacedent
    doreplacedent.add(catPart);
}

See More Examples