Example usage for com.lowagie.text.pdf PdfStamper setFormFlattening

List of usage examples for com.lowagie.text.pdf PdfStamper setFormFlattening

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfStamper setFormFlattening.

Prototype

public void setFormFlattening(boolean flat) 

Source Link

Document

Determines if the fields are flattened on close.

Usage

From source file:org.ofbiz.content.survey.PdfSurveyServices.java

License:Apache License

/**
 *//*from  w  w  w .j a  va 2  s. com*/
public static Map<String, Object> getAcroFieldsFromPdf(DispatchContext dctx,
        Map<String, ? extends Object> context) {
    Map<String, Object> acroFieldMap = FastMap.newInstance();
    try {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        Delegator delegator = dctx.getDelegator();
        ByteBuffer byteBuffer = getInputByteBuffer(context, delegator);
        PdfReader r = new PdfReader(byteBuffer.array());
        PdfStamper s = new PdfStamper(r, os);
        AcroFields fs = s.getAcroFields();
        Map<String, Object> map = UtilGenerics.checkMap(fs.getFields());
        s.setFormFlattening(true);

        // Debug code to get the values for setting TDP
        //        String[] sa = fs.getAppearanceStates("TDP");
        //        for (int i=0;i<sa.length;i++)
        //            Debug.logInfo("Appearance="+sa[i]);

        for (String fieldName : map.keySet()) {
            String parmValue = fs.getField(fieldName);
            acroFieldMap.put(fieldName, parmValue);
        }

    } catch (DocumentException e) {
        System.err.println(e.getMessage());
        return ServiceUtil.returnError(e.getMessage());
    } catch (GeneralException e) {
        System.err.println(e.getMessage());
        return ServiceUtil.returnError(e.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
        return ServiceUtil.returnError(ioe.getMessage());
    }

    Map<String, Object> results = ServiceUtil.returnSuccess();
    results.put("acroFieldMap", acroFieldMap);
    return results;
}

From source file:org.ofbiz.content.survey.PdfSurveyServices.java

License:Apache License

/**
 *///from  w w w. ja  v a  2s.  com
public static Map<String, Object> setAcroFields(DispatchContext dctx, Map<String, ? extends Object> context) {
    Map<String, Object> results = ServiceUtil.returnSuccess();
    Delegator delegator = dctx.getDelegator();
    try {
        Map<String, Object> acroFieldMap = UtilGenerics.checkMap(context.get("acroFieldMap"));
        ByteBuffer byteBuffer = getInputByteBuffer(context, delegator);
        PdfReader r = new PdfReader(byteBuffer.array());
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfStamper s = new PdfStamper(r, baos);
        AcroFields fs = s.getAcroFields();
        Map<String, Object> map = UtilGenerics.checkMap(fs.getFields());
        s.setFormFlattening(true);

        // Debug code to get the values for setting TDP
        //      String[] sa = fs.getAppearanceStates("TDP");
        //      for (int i=0;i<sa.length;i++)
        //          Debug.logInfo("Appearance="+sa[i]);

        for (String fieldName : map.keySet()) {
            String fieldValue = fs.getField(fieldName);
            Object obj = acroFieldMap.get(fieldName);
            if (obj instanceof Date) {
                Date d = (Date) obj;
                fieldValue = UtilDateTime.toDateString(d);
            } else if (obj instanceof Long) {
                Long lg = (Long) obj;
                fieldValue = lg.toString();
            } else if (obj instanceof Integer) {
                Integer ii = (Integer) obj;
                fieldValue = ii.toString();
            } else {
                fieldValue = (String) obj;
            }

            if (UtilValidate.isNotEmpty(fieldValue)) {
                fs.setField(fieldName, fieldValue);
            }
        }

        s.close();
        baos.close();
        ByteBuffer outByteBuffer = ByteBuffer.wrap(baos.toByteArray());
        results.put("outByteBuffer", outByteBuffer);
    } catch (DocumentException e) {
        System.err.println(e.getMessage());
        results = ServiceUtil.returnError(e.getMessage());
    } catch (GeneralException e) {
        System.err.println(e.getMessage());
        results = ServiceUtil.returnError(e.getMessage());
    } catch (FileNotFoundException e) {
        System.err.println(e.getMessage());
        results = ServiceUtil.returnError(e.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
        results = ServiceUtil.returnError(ioe.getMessage());
    } catch (Exception ioe) {
        System.err.println(ioe.getMessage());
        results = ServiceUtil.returnError(ioe.getMessage());
    }
    return results;
}

From source file:org.openelis.bean.WorksheetPrintReportBean.java

License:Open Source License

private Path fillPDFWorksheet(Integer worksheetId, String templateName, String userName) throws Exception {
    int i, j, formCapacity, diagramCapacity, pageNumber;
    AcroFields form;/*from w  w w .  j  a va  2s. c  om*/
    AnalysisViewDO aVDO;
    ArrayList<AnalysisQaEventViewDO> aqeVDOs;
    ArrayList<Integer> analysisIds, qcLotIds;
    ArrayList<NoteViewDO> nVDOs;
    ArrayList<QcAnalyteViewDO> qaVDOs;
    ArrayList<QcLotViewDO> qlVDOs;
    ArrayList<SampleManager1> sMans;
    ArrayList<SampleOrganizationViewDO> sOrgs;
    ArrayList<SampleQaEventViewDO> sqeVDOs;
    ArrayList<SystemVariableDO> sysVars;
    ArrayList<WorksheetAnalysisViewDO> waVDOs;
    ByteArrayOutputStream page;
    Document doc;
    HashMap<Integer, ArrayList<QcAnalyteViewDO>> qaVDOMap;
    HashMap<Integer, ArrayList<WorksheetAnalysisViewDO>> waVDOMap;
    HashMap<Integer, QcLotViewDO> qlMap;
    HashMap<Integer, SampleManager1> sMap;
    OutputStream out;
    Path path;
    PatientDO patDO;
    PdfCopy writer;
    PdfReader reader;
    PdfStamper stamper;
    ProviderDO proDO;
    QcLotViewDO qlVDO;
    RandomAccessFileOrArray original;
    SampleEnvironmentalDO seDO;
    SampleDO sDO;
    SampleItemViewDO siVDO;
    SampleManager1 sMan;
    String collectionDateTime, dirName, now, qcLink;
    StringBuilder aNotes, aQaevents, sNotes, sQaevents;
    WorksheetAnalysisDO waDO1;
    WorksheetItemDO wiDO1;
    WorksheetManager1 wMan;
    WorksheetViewDO wVDO;

    now = ReportUtil.toString(new Date(), Messages.get().dateTimePattern());

    dirName = "";
    try {
        sysVars = systemVariable.fetchByName("worksheet_template_directory", 1);
        if (sysVars.size() > 0)
            dirName = ((SystemVariableDO) sysVars.get(0)).getValue();
    } catch (Exception anyE) {
        throw new Exception("Error retrieving temp directory variable: " + anyE.getMessage());
    }

    analysisIds = new ArrayList<Integer>();
    qcLotIds = new ArrayList<Integer>();
    waVDOMap = new HashMap<Integer, ArrayList<WorksheetAnalysisViewDO>>();
    wMan = worksheetManager.fetchById(worksheetId, WorksheetManager1.Load.DETAIL,
            WorksheetManager1.Load.REAGENT);
    for (WorksheetAnalysisViewDO data : WorksheetManager1Accessor.getAnalyses(wMan)) {
        waVDOs = waVDOMap.get(data.getWorksheetItemId());
        if (waVDOs == null) {
            waVDOs = new ArrayList<WorksheetAnalysisViewDO>();
            waVDOMap.put(data.getWorksheetItemId(), waVDOs);
        }
        waVDOs.add(data);

        if (data.getAnalysisId() != null)
            analysisIds.add(data.getAnalysisId());
        else if (data.getQcLotId() != null)
            qcLotIds.add(data.getQcLotId());
    }

    sMap = new HashMap<Integer, SampleManager1>();
    if (analysisIds.size() > 0) {
        sMans = sampleManager.fetchByAnalyses(analysisIds, SampleManager1.Load.ORGANIZATION,
                SampleManager1.Load.QA, SampleManager1.Load.NOTE, SampleManager1.Load.SINGLEANALYSIS,
                SampleManager1.Load.PROVIDER);
        for (SampleManager1 data : sMans) {
            for (AnalysisViewDO data1 : SampleManager1Accessor.getAnalyses(data))
                sMap.put(data1.getId(), data);
        }
    }

    qaVDOMap = new HashMap<Integer, ArrayList<QcAnalyteViewDO>>();
    qlMap = new HashMap<Integer, QcLotViewDO>();
    if (qcLotIds.size() > 0) {
        qlVDOs = qcLot.fetchByIds(qcLotIds);
        for (QcLotViewDO data : qlVDOs) {
            qlMap.put(data.getId(), data);
            try {
                qaVDOs = qcAnalyte.fetchByQcId(data.getQcId());
                qaVDOMap.put(data.getQcId(), qaVDOs);
            } catch (NotFoundException nfE) {
                // ignore this error as leaving the hash record blank will not
                // cause an error due to a null check later on in the code
            }
        }
    }

    formCapacity = 1;
    out = null;
    try {
        path = ReportUtil.createTempFile("worksheetPrint", ".pdf", null);
        out = Files.newOutputStream(path);

        reader = new PdfReader(dirName + "OEWorksheet" + templateName + ".pdf");
        original = reader.getSafeFile();

        form = reader.getAcroFields();
        if (form.getField("capacity") != null)
            formCapacity = Integer.parseInt(form.getField("capacity"));
        if (form.getField("diagram_capacity") != null)
            diagramCapacity = Integer.parseInt(form.getField("diagram_capacity"));
        else
            diagramCapacity = formCapacity;

        doc = new Document(reader.getPageSizeWithRotation(1));
        writer = new PdfCopy(doc, out);
        doc.open();
        reader.close();

        i = -1;
        pageNumber = -1;
        form = null;
        page = null;
        stamper = null;
        wVDO = wMan.getWorksheet();
        for (WorksheetItemDO wiDO : WorksheetManager1Accessor.getItems(wMan)) {
            j = wiDO.getPosition() % diagramCapacity;
            if (j == 0)
                j = diagramCapacity;
            for (WorksheetAnalysisViewDO waVDO : waVDOMap.get(wiDO.getId())) {
                if (i == -1 || i > formCapacity || j > diagramCapacity) {
                    if (i != -1) {
                        fillReagentFields(form, wMan);
                        stamper.setFormFlattening(true);
                        renameFields(form, pageNumber);
                        flattenFilledFields(stamper, form, formCapacity, pageNumber);
                        stamper.close();
                        reader.close();
                        reader = new PdfReader(page.toByteArray());
                        writer.addPage(writer.getImportedPage(reader, 1));
                        reader.close();
                    }
                    reader = new PdfReader(original, null);
                    page = new ByteArrayOutputStream();
                    stamper = new PdfStamper(reader, page);
                    form = stamper.getAcroFields();
                    i = 1;
                    pageNumber++;

                    form.setField("current_date_time", now);
                    form.setField("username", userName);
                    form.setField("worksheet_description_1", wVDO.getDescription());
                }

                qcLink = "";
                if (waVDO.getWorksheetAnalysisId() != null) {
                    try {
                        waDO1 = worksheetAnalysis.fetchById(waVDO.getWorksheetAnalysisId());
                        wiDO1 = worksheetItem.fetchById(waDO1.getWorksheetItemId());
                        qcLink = waDO1.getAccessionNumber() + " (" + wiDO1.getPosition() + ")";
                    } catch (Exception anyE) {
                        log.log(Level.SEVERE, anyE.getMessage(), anyE);
                    }
                }

                form.setField("worksheet_id_" + (i), wVDO.getId().toString());
                form.setField("created_date_" + (i),
                        ReportUtil.toString(wVDO.getCreatedDate(), Messages.get().dateTimePattern()));
                if (waVDOMap.get(wiDO.getId()).indexOf(waVDO) == 0)
                    form.setField("position_" + (i), wiDO.getPosition().toString());

                if (waVDO.getAnalysisId() != null) {
                    sMan = sMap.get(waVDO.getAnalysisId());
                    sDO = sMan.getSample();
                    patDO = null;
                    proDO = null;
                    seDO = null;
                    if (Constants.domain().CLINICAL.equals(sDO.getDomain())) {
                        patDO = sMan.getSampleClinical().getPatient();
                        proDO = sMan.getSampleClinical().getProvider();
                    } else if (Constants.domain().NEONATAL.equals(sDO.getDomain())) {
                        patDO = sMan.getSampleNeonatal().getPatient();
                        proDO = sMan.getSampleNeonatal().getProvider();
                    } else if (Constants.domain().ENVIRONMENTAL.equals(sDO.getDomain())) {
                        seDO = sMan.getSampleEnvironmental();
                    }
                    sOrgs = SampleManager1Accessor.getOrganizations(sMan);
                    aVDO = (AnalysisViewDO) sMan.getObject(Constants.uid().getAnalysis(waVDO.getAnalysisId()));
                    siVDO = (SampleItemViewDO) sMan
                            .getObject(Constants.uid().getSampleItem(aVDO.getSampleItemId()));

                    sQaevents = new StringBuilder();
                    sqeVDOs = SampleManager1Accessor.getSampleQAs(sMan);
                    if (sqeVDOs != null && sqeVDOs.size() > 0) {
                        for (SampleQaEventViewDO sqeVDO : sqeVDOs) {
                            if (sQaevents.length() > 0)
                                sQaevents.append(" | ");
                            sQaevents.append(sqeVDO.getQaEventName());
                        }
                    }

                    aQaevents = new StringBuilder();
                    aqeVDOs = SampleManager1Accessor.getAnalysisQAs(sMan);
                    if (aqeVDOs != null && aqeVDOs.size() > 0) {
                        for (AnalysisQaEventViewDO aqeVDO : aqeVDOs) {
                            if (!waVDO.getAnalysisId().equals(aqeVDO.getAnalysisId()))
                                continue;
                            if (aQaevents.length() > 0)
                                aQaevents.append(" | ");
                            aQaevents.append(aqeVDO.getQaEventName());
                        }
                    }

                    sNotes = new StringBuilder();
                    nVDOs = new ArrayList<NoteViewDO>();
                    if (SampleManager1Accessor.getSampleInternalNotes(sMan) != null)
                        nVDOs.addAll(SampleManager1Accessor.getSampleInternalNotes(sMan));
                    if (SampleManager1Accessor.getSampleExternalNote(sMan) != null)
                        nVDOs.add(SampleManager1Accessor.getSampleExternalNote(sMan));
                    if (nVDOs != null && nVDOs.size() > 0) {
                        for (NoteViewDO nVDO : nVDOs) {
                            if (sNotes.length() > 0)
                                sNotes.append(" | ");
                            sNotes.append(nVDO.getText());
                        }
                    }

                    aNotes = new StringBuilder();
                    nVDOs = new ArrayList<NoteViewDO>();
                    if (SampleManager1Accessor.getAnalysisInternalNotes(sMan) != null)
                        nVDOs.addAll(SampleManager1Accessor.getAnalysisInternalNotes(sMan));
                    if (SampleManager1Accessor.getAnalysisExternalNotes(sMan) != null)
                        nVDOs.addAll(SampleManager1Accessor.getAnalysisExternalNotes(sMan));
                    if (nVDOs != null && nVDOs.size() > 0) {
                        for (NoteViewDO nVDO : nVDOs) {
                            if (!waVDO.getAnalysisId().equals(nVDO.getReferenceId()))
                                continue;
                            if (aNotes.length() > 0)
                                aNotes.append(" | ");
                            aNotes.append(nVDO.getText());
                        }
                    }

                    if (waVDOMap.get(wiDO.getId()).size() > 1)
                        form.setField("well_label_" + (j), wiDO.getPosition().toString());
                    else
                        form.setField("well_label_" + (j), sDO.getAccessionNumber().toString());
                    form.setField("accession_number_" + (i), sDO.getAccessionNumber().toString());
                    form.setField("qc_link_" + (i), qcLink);
                    if (sDO.getCollectionDate() != null) {
                        collectionDateTime = ReportUtil.toString(sDO.getCollectionDate(),
                                Messages.get().datePattern());
                        if (sDO.getCollectionTime() != null) {
                            collectionDateTime += " ";
                            collectionDateTime += ReportUtil.toString(sDO.getCollectionTime(),
                                    Messages.get().timePattern());
                        }
                        form.setField("collection_date_" + (i), collectionDateTime);
                    }
                    form.setField("received_date_" + (i),
                            ReportUtil.toString(sDO.getReceivedDate(), Messages.get().dateTimePattern()));
                    if (patDO != null) {
                        form.setField("patient_last_" + (i), patDO.getLastName());
                        form.setField("patient_first_" + (i), patDO.getFirstName());
                    }
                    if (proDO != null) {
                        form.setField("provider_last_" + (i), proDO.getLastName());
                        form.setField("provider_first_" + (i), proDO.getFirstName());
                    }
                    if (seDO != null) {
                        form.setField("env_location_" + (i), seDO.getLocation());
                        form.setField("env_description_" + (i), seDO.getDescription());
                    }
                    if (sOrgs != null && sOrgs.size() > 0) {
                        for (SampleOrganizationViewDO soVDO : sOrgs) {
                            if (Constants.dictionary().ORG_REPORT_TO.equals(soVDO.getTypeId()))
                                form.setField("organization_name_" + (i), soVDO.getOrganizationName());
                            else if (Constants.dictionary().ORG_BILL_TO.equals(soVDO.getTypeId()))
                                form.setField("bill_to_name_" + (i), soVDO.getOrganizationName());
                        }
                    }
                    form.setField("type_of_sample_" + (i), siVDO.getTypeOfSample());
                    form.setField("source_of_sample_" + (i), siVDO.getSourceOfSample());
                    form.setField("source_other_" + (i), siVDO.getSourceOther());
                    form.setField("container_reference_" + (i), siVDO.getContainerReference());
                    form.setField("test_" + (i), aVDO.getTestName());
                    form.setField("method_" + (i), aVDO.getMethodName());
                    form.setField("sample_qaevent_" + (i), sQaevents.toString());
                    form.setField("analysis_qaevent_" + (i), aQaevents.toString());
                    form.setField("sample_note_" + (i), sNotes.toString());
                    form.setField("analysis_note_" + (i), aNotes.toString());
                } else if (waVDO.getQcLotId() != null) {
                    qlVDO = qlMap.get(waVDO.getQcLotId());
                    form.setField("well_label_" + (j), qlVDO.getQcName());
                    form.setField("qc_link_" + (i), qcLink);
                    form.setField("qc_name_" + (i), qlVDO.getQcName());
                    form.setField("qc_lot_" + (i), qlVDO.getLotNumber());
                    form.setField("qc_usable_" + (i),
                            ReportUtil.toString(qlVDO.getUsableDate(), Messages.get().dateTimePattern()));
                    form.setField("qc_expiration_" + (i),
                            ReportUtil.toString(qlVDO.getExpireDate(), Messages.get().dateTimePattern()));
                    qaVDOs = qaVDOMap.get(qlVDO.getQcId());
                    if (qaVDOs != null && !qaVDOs.isEmpty())
                        form.setField("qc_expected_value_" + (i), qaVDOs.get(0).getValue());
                }
                i++;
            }
        }
        fillReagentFields(form, wMan);
        stamper.setFormFlattening(true);
        renameFields(form, pageNumber);
        flattenFilledFields(stamper, form, formCapacity, pageNumber);
        stamper.close();
        reader.close();

        reader = new PdfReader(page.toByteArray());
        writer.addPage(writer.getImportedPage(reader, 1));
        doc.close();
        reader.close();
    } finally {
        try {
            if (out != null)
                out.close();
        } catch (Exception e) {
            log.severe("Could not close output stream for worksheet print report");
        }
    }
    return path;
}

From source file:org.orbeon.oxf.processor.pdf.PDFTemplateProcessor.java

License:Open Source License

protected void readInput(PipelineContext pipelineContext, ProcessorInput input, Config config,
        OutputStream outputStream) {
    final org.dom4j.Document configDocument = readCacheInputAsDOM4J(pipelineContext, "model");// TODO: after all, should we use "config"?
    final org.dom4j.Document instanceDocument = readInputAsDOM4J(pipelineContext, input);

    final Configuration configuration = XPathCache.getGlobalConfiguration();
    final DocumentInfo configDocumentInfo = new DocumentWrapper(configDocument, null, configuration);
    final DocumentInfo instanceDocumentInfo = new DocumentWrapper(instanceDocument, null, configuration);

    try {/*w ww.  j  ava  2  s.co m*/
        // Get reader
        final String templateHref = XPathCache.evaluateAsString(configDocumentInfo, "/*/template/@href", null,
                null, functionLibrary, null, null, null);//TODO: LocationData

        // Create PDF reader
        final PdfReader reader;
        {
            final String inputName = ProcessorImpl.getProcessorInputSchemeInputName(templateHref);
            if (inputName != null) {
                // Read the input
                final ByteArrayOutputStream os = new ByteArrayOutputStream();
                readInputAsSAX(pipelineContext, inputName,
                        new BinaryTextXMLReceiver(null, os, true, false, null, false, false, null, false));

                // Create the reader
                reader = new PdfReader(os.toByteArray());
            } else {
                // Read and create the reader
                reader = new PdfReader(URLFactory.createURL(templateHref));
            }
        }

        // Get total number of pages
        final int pageCount = reader.getNumberOfPages();

        // Get size of first page
        final Rectangle pageSize = reader.getPageSize(1);
        final float width = pageSize.getWidth();
        final float height = pageSize.getHeight();

        final String showGrid = XPathCache.evaluateAsString(configDocumentInfo, "/*/template/@show-grid", null,
                null, functionLibrary, null, null, null);//TODO: LocationData

        final PdfStamper stamper = new PdfStamper(reader, outputStream);
        stamper.setFormFlattening(true);

        for (int currentPage = 1; currentPage <= pageCount; currentPage++) {
            final PdfContentByte contentByte = stamper.getOverContent(currentPage);
            // Handle root group
            final GroupContext initialGroupContext = new GroupContext(contentByte, stamper.getAcroFields(),
                    height, currentPage, Collections.singletonList((Item) instanceDocumentInfo), 1, 0, 0,
                    "Courier", 14, 15.9f);
            handleGroup(pipelineContext, initialGroupContext,
                    Dom4jUtils.elements(configDocument.getRootElement()), functionLibrary, reader);

            // Handle preview grid (NOTE: This can be heavy in memory.)
            if ("true".equalsIgnoreCase(showGrid)) {
                final float topPosition = 10f;

                final BaseFont baseFont2 = BaseFont.createFont("Courier", BaseFont.CP1252,
                        BaseFont.NOT_EMBEDDED);
                contentByte.beginText();
                {
                    // 20-pixel lines and side legends

                    contentByte.setFontAndSize(baseFont2, (float) 7);

                    for (int w = 0; w <= width; w += 20) {
                        for (int h = 0; h <= height; h += 2)
                            contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, ".", (float) w, height - h,
                                    0);
                    }
                    for (int h = 0; h <= height; h += 20) {
                        for (int w = 0; w <= width; w += 2)
                            contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, ".", (float) w, height - h,
                                    0);
                    }

                    for (int w = 0; w <= width; w += 20) {
                        contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, "" + w, (float) w,
                                height - topPosition, 0);
                        contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, "" + w, (float) w, topPosition,
                                0);
                    }
                    for (int h = 0; h <= height; h += 20) {
                        contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, "" + h, (float) 5, height - h,
                                0);
                        contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, "" + h, width - (float) 5,
                                height - h, 0);
                    }

                    // 10-pixel lines

                    contentByte.setFontAndSize(baseFont2, (float) 3);

                    for (int w = 10; w <= width; w += 10) {
                        for (int h = 0; h <= height; h += 2)
                            contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, ".", (float) w, height - h,
                                    0);
                    }
                    for (int h = 10; h <= height; h += 10) {
                        for (int w = 0; w <= width; w += 2)
                            contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, ".", (float) w, height - h,
                                    0);
                    }
                }
                contentByte.endText();
            }
        }

        // Close the document
        //            document.close();
        stamper.close();
    } catch (Exception e) {
        throw new OXFException(e);
    }
}

From source file:questions.forms.RemoveXfa.java

@SuppressWarnings("unchecked")
public static void main(String[] args) {
    try {/*w ww .  jav a  2  s .c  o  m*/
        PdfReader reader = new PdfReader(RESOURCE);
        PdfDictionary root = reader.getCatalog();
        PdfDictionary acroform = root.getAsDict(PdfName.ACROFORM);
        acroform.remove(PdfName.XFA);
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT));
        AcroFields form = stamper.getAcroFields();
        Map<String, Item> fields = form.getFields();
        for (String field : fields.keySet()) {
            System.out.println(field);
            form.setField(field, "value");
        }
        stamper.partialFormFlattening("topmostSubform[0].Page1[0].SN_NUMBER[0]");
        stamper.setFormFlattening(true);
        stamper.close();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }
}

From source file:questions.javascript.RemoveJavaScript.java

public static void main(String[] args) throws DocumentException, IOException {
    // creating the form with JS
    AddJavaScriptToForm.main(args);/*from   ww w.j  ava  2s  .c o m*/
    // removing the document level JS
    PdfReader reader = new PdfReader(AddJavaScriptToForm.RESULT);
    PdfDictionary root = reader.getCatalog();
    PdfDictionary names = root.getAsDict(PdfName.NAMES);
    names.remove(PdfName.JAVASCRIPT);
    if (names.size() == 0) {
        root.remove(PdfName.NAMES);
    }
    reader.removeUnusedObjects();
    // filling out and flattening the form
    // (if you don't flatten, you'll get JS errors!)
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT));
    AcroFields form = stamper.getAcroFields();
    form.setField("married", "no");
    stamper.setFormFlattening(true);
    stamper.close();
}

From source file:ud.ing.modi.controlador.ptorecarga.GeneracionFactura.java

public void generacionFacturaPDF() {
    try {//w  w  w. j a  v a  2  s.c  o m
        System.out.println("Generaa");
        cargarDatosFactura();

        if (this.factura != null) {

            PdfReader reader = new PdfReader(
                    "C:\\Users\\Administrador\\Dropbox\\Tesis\\Monedero Digital\\Factura_PtoRecarga.pdf");
            String nombreFact = "D:\\REPOSITORIO TESIS2\\REPO\\MONEDERO_DIGITAL_APP\\MONEDERO_DIGITAL_APP_WEB\\src\\main\\webapp\\docs\\FACTURA_"
                    + traerUsu() + ".pdf";
            PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(nombreFact));
            AcroFields formulario = stamp.getAcroFields();

            formulario.setField("NUM_FACTURA", Integer.toString(this.factura.getCodFactura()));

            int mes = this.factura.getFechaCorte().getMonth() + 1;
            int anio = this.factura.getFechaCorte().getYear() + 1900;
            String fechaC = this.factura.getFechaCorte().getDate() + "-" + mes + "-" + anio;
            formulario.setField("FECHA_CORTE", fechaC);
            mes = this.factura.getFechaVencimiento().getMonth() + 1;
            anio = this.factura.getFechaVencimiento().getYear() + 1900;
            String fechaL = this.factura.getFechaVencimiento().getDate() + "-" + mes + "-" + anio;
            formulario.setField("FECHA_LIMITE", fechaL);
            formulario.setField("VALOR_PAGO", "$ " + Double.toString(this.factura.getValorTotalPago()));
            formulario.setField("COD_CLIENTE", Integer.toString(this.factura.getPuntoRecarga().getIdCliente()));
            formulario.setField("NOMBRE_CLIENTE", this.factura.getPuntoRecarga().getRazonSocial());
            formulario.setField("NUM_RECARGAS", Integer.toString(this.factura.getNumTotalRecargas()));
            formulario.setField("VALOR_RECARGAS", "$ " + Double.toString(this.factura.getValorTotalRecargas()));
            formulario.setField("VALOR_COMISION",
                    "$ " + Double.toString(this.factura.getValorCalculoComision()));

            stamp.setFormFlattening(true);
            stamp.close();

        }

    } catch (IOException ex) {
        Logger.getLogger(GeneracionFactura.class.getName()).log(Level.SEVERE, null, ex);
    } catch (DocumentException ex) {
        Logger.getLogger(GeneracionFactura.class.getName()).log(Level.SEVERE, null, ex);
    }
}