List of usage examples for com.itextpdf.text.pdf PdfStamper close
public void close() throws DocumentException, IOException
From source file:de.earthdawn.ECEPdfExporter.java
License:Open Source License
public void exportAjfelMordom(EDCHARACTER edCharakter, int pdftype, File outFile) throws DocumentException, IOException { File pdfinputfile;//from w ww. j av a2s.c om if (pdftype == 1) pdfinputfile = new File("templates/ed3_character_sheet_Ajfel+Mordom_pl.pdf"); else pdfinputfile = new File("templates/ed3_character_sheet_Ajfel+Mordom.pdf"); PdfReader reader = new PdfReader(new FileInputStream(pdfinputfile)); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outFile)); acroFields = stamper.getAcroFields(); CharacterContainer character = new CharacterContainer(edCharakter); // +++ DEBUG +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //Set<String> fieldNames = acroFields.getFields().keySet(); //fieldNames = new TreeSet<String>(fieldNames); //for( String fieldName : fieldNames ) { // acroFields.setField( fieldName, fieldName ); //} // +++ ~DEBUG ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ exportCommonFields(character, 16, 40); setButtons(character.getWound().getNormal(), "Wound.", 7); acroFields.setField("BloodWound", "D:" + character.getHealth().getBlooddamage() + ", W:" + character.getWound().getBlood() + ", DR:" + character.getHealth().getDepatterningrate()); // Charakter Potrait-Bild einfgen List<Base64BinaryType> potraits = character.getPortrait(); if (!potraits.isEmpty()) { Image image = Image.getInstance(potraits.get(0).getValue()); if (image != null) { image.setAbsolutePosition(18.5f, 702.5f); image.scaleAbsolute(91.5f, 93f); PdfContentByte overContent = stamper.getOverContent(2); if (overContent != null) overContent.addImage(image); else errorout.println("Unable to insert character image."); } } int counterArmor = 0; for (ARMORType armor : character.getProtection().getARMOROrSHIELD()) { if (!armor.getUsed().equals(YesnoType.YES)) continue; int physicalarmor = armor.getPhysicalarmor(); int mysticarmor = armor.getMysticarmor(); int penalty = armor.getPenalty(); if ((physicalarmor == 0) && (mysticarmor == 0) && (penalty == 0)) continue; acroFields.setField("ArmorName." + counterArmor, armor.getName()); acroFields.setField("ArmorPhysical." + counterArmor, String.valueOf(physicalarmor)); acroFields.setField("ArmorMystic." + counterArmor, String.valueOf(mysticarmor)); acroFields.setField("ArmorPenalty." + counterArmor, String.valueOf(penalty)); counterArmor++; } acroFields.setField("Discipline", concat(" / ", character.getDisciplineNames())); acroFields.setField("Circle", concat(" / ", character.getDisciplineCircles())); acroFields.setField("HalfMagic", character.getAllHalfMagic()); List<WEAPONType> weapons = character.getWeapons(); if (weapons != null) { int counter = 0; ATTRIBUTEType str = character.getAttributes().get("STR"); for (WEAPONType weapon : weapons) { acroFields.setField("Weapon." + counter, weapon.getName()); acroFields.setField("WeaponStrength." + counter, String.valueOf(str.getStep())); acroFields.setField("WeaponDamage.0." + counter, String.valueOf(weapon.getDamagestep())); acroFields.setField("WeaponDamage.1." + counter, String.valueOf(weapon.getDamagestep() + str.getStep())); acroFields.setField("WeaponRange." + counter, weapon.getShortrange() + " / " + weapon.getLongrange()); counter++; } } counterEquipment = 0; for (ITEMType item : listArmorAndWeapon(character)) addEquipment(item.getName(), item.getWeight()); for (ITEMType item : character.getItems()) addEquipment(item.getName(), item.getWeight()); for (MAGICITEMType item : character.getMagicItem()) { StringBuffer text = new StringBuffer(item.getName()); text.append(" ("); text.append(item.getBlooddamage()); text.append("/"); text.append(item.getDepatterningrate()); text.append("/"); text.append(item.getEnchantingdifficultynumber()); text.append(")"); addEquipment(text.toString(), item.getWeight()); } String copperPieces = null; String goldPieces = null; String silverPieces = null; int otherPieces = 0; for (COINSType coins : character.getAllCoins()) { StringBuffer other = new StringBuffer(); if (coins.getEarth() > 0) other.append(" earth:" + coins.getEarth()); if (coins.getWater() > 0) other.append(" water:" + coins.getWater()); if (coins.getAir() > 0) other.append(" air:" + coins.getAir()); if (coins.getFire() > 0) other.append(" fire:" + coins.getFire()); if (coins.getOrichalcum() > 0) other.append(" orichalcum:" + coins.getOrichalcum()); if (coins.getGem50() > 0) other.append(" gem50:" + coins.getGem50()); if (coins.getGem100() > 0) other.append(" gem100:" + coins.getGem100()); if (coins.getGem200() > 0) other.append(" gem200:" + coins.getGem200()); if (coins.getGem500() > 0) other.append(" gem500:" + coins.getGem500()); if (coins.getGem1000() > 0) other.append(" gem1000:" + coins.getGem1000()); if (!other.toString().isEmpty()) { if (!coins.getName().isEmpty()) other.append(" [" + coins.getName() + "]"); acroFields.setField("Coins." + String.valueOf(otherPieces), other.toString()); otherPieces++; } if (coins.getCopper() != 0) { if (copperPieces == null) { copperPieces = String.valueOf(coins.getCopper()); } else { copperPieces += "+" + String.valueOf(coins.getCopper()); } } if (coins.getSilver() != 0) { if (silverPieces == null) { silverPieces = String.valueOf(coins.getSilver()); } else { silverPieces += "+" + String.valueOf(coins.getSilver()); } } if (coins.getGold() != 0) { if (goldPieces == null) { goldPieces = String.valueOf(coins.getGold()); } else { goldPieces += "+" + String.valueOf(coins.getGold()); } } } acroFields.setField("CopperPieces", copperPieces); acroFields.setField("SilverPieces.0", silverPieces); acroFields.setField("GoldPieces", goldPieces); List<List<SPELLType>> spellslist = new ArrayList<List<SPELLType>>(); spellslist.add(character.getOpenSpellList()); int counterDisciplinetalent = 0; int counterOthertalent = 0; int counterKnack = 0; for (DISCIPLINEType discipline : character.getDisciplines()) { List<TALENTType> disziplinetalents = discipline.getDISZIPLINETALENT(); Collections.sort(disziplinetalents, new TalentComparator()); for (TALENTType talent : disziplinetalents) { // Fr mehr als 20 Disziplintalente ist kein Platz! if (counterDisciplinetalent > 20) break; setTalent(counterDisciplinetalent, talent, character.getAttributes()); counterDisciplinetalent++; for (KNACKType knack : talent.getKNACK()) { acroFields.setField("TalentKnackTalent." + counterKnack, talent.getName()); acroFields.setField("TalentKnackName." + counterKnack, knack.getName() + " [" + knack.getStrain() + "]"); counterKnack++; } } List<TALENTType> optionaltalents = discipline.getOPTIONALTALENT(); Collections.sort(optionaltalents, new TalentComparator()); for (TALENTType talent : optionaltalents) { setTalent(20 + counterOthertalent, talent, character.getAttributes()); if (talent.getKarma().equals(YesnoType.YES)) { acroFields.setField("KarmaRequired." + counterOthertalent, "Yes"); } else { acroFields.setField("KarmaRequired." + counterOthertalent, ""); } counterOthertalent++; for (KNACKType knack : talent.getKNACK()) { acroFields.setField("TalentKnackTalent." + counterKnack, talent.getName()); acroFields.setField("TalentKnackName." + counterKnack, knack.getName() + " [" + knack.getStrain() + "]"); counterKnack++; } } spellslist.add(discipline.getSPELL()); } setSpellAjfelMordom(spellslist); // Die eventuell gesetzte KarmaBentigtHarken lschen while (counterOthertalent < 17) { acroFields.setField("KarmaRequired." + counterOthertalent, ""); counterOthertalent++; } int counterMagicItem = 0; for (THREADITEMType item : character.getThreadItem()) { int counterMagicItemRank = 0; for (THREADRANKType rank : item.getTHREADRANK()) { counterMagicItemRank++; acroFields.setField("ThreadMagicObject." + counterMagicItem, item.getName()); acroFields.setField("ThreadMagicRank." + counterMagicItem, String.valueOf(counterMagicItemRank)); acroFields.setField("ThreadMagicLPCost." + counterMagicItem, String.valueOf(rank.getLpcost())); acroFields.setField("ThreadMagicEffect." + counterMagicItem, rank.getEffect()); counterMagicItem++; } } int counterBloodCharms = 0; for (MAGICITEMType item : character.getBloodCharmItem()) { acroFields.setField("BloodMagicType." + counterBloodCharms, item.getName()); String used = ""; if (item.getUsed().equals(YesnoType.YES)) used = " (in use)"; acroFields.setField("BloodMagicDamage." + counterBloodCharms, item.getBlooddamage() + used); acroFields.setField("BloodMagicEffect." + counterBloodCharms, item.getEffect()); counterBloodCharms++; } acroFields.setField("ShortDescription", character.getDESCRIPTION()); int counterLanguageSpeak = 0; int counterLanguageReadwrite = 0; for (CHARACTERLANGUAGEType language : character.getLanguages().getLanguages()) { if (!language.getSpeak().equals(LearnedbyType.NO)) { acroFields.setField("LanguagesSpeak." + counterLanguageSpeak, language.getLanguage()); counterLanguageSpeak++; } if (!language.getReadwrite().equals(LearnedbyType.NO)) { acroFields.setField("LanguagesReadWrite." + counterLanguageReadwrite, language.getLanguage()); counterLanguageReadwrite++; } } stamper.close(); }
From source file:de.earthdawn.ECEPdfExporter.java
License:Open Source License
public void exportSpellcards(EDCHARACTER edCharakter, File outFile, int version) throws DocumentException, IOException { CharacterContainer character = new CharacterContainer(edCharakter); File template = null;/*from www . j av a 2 s . c o m*/ int maxSpellPerPage = 1; switch (version) { case 0: default: template = new File("./templates/spellcards_portrait_2x2.pdf"); maxSpellPerPage = 4; break; case 1: template = new File("./templates/spellcards_landscape_2x2.pdf"); maxSpellPerPage = 4; break; } String filename = outFile.getCanonicalPath(); String filenameBegin = ""; String filenameEnd = ""; int dotPosition = filename.lastIndexOf('.'); if (dotPosition >= 0) { filenameBegin = filename.substring(0, dotPosition); filenameEnd = filename.substring(dotPosition); } else { filenameBegin = filename; } int counterFile = 0; int counterSpells = maxSpellPerPage; PdfStamper stamper = null; PdfReader reader = null; HashMap<String, SpelldescriptionType> spelldescriptions = ApplicationProperties.create() .getSpellDescriptions(); List<List<SPELLType>> spellslist = new ArrayList<List<SPELLType>>(); List<String> disciplineNames = new ArrayList<String>(); spellslist.add(character.getOpenSpellList()); disciplineNames.add(""); for (DISCIPLINEType discipline : character.getDisciplines()) { spellslist.add(discipline.getSPELL()); disciplineNames.add(discipline.getName()); } int spelllistnr = 0; for (List<SPELLType> spells : spellslist) { Collections.sort(spells, new SpellComparator()); for (SPELLType spell : spells) { if (counterSpells < maxSpellPerPage) { counterSpells++; } else { if (stamper != null) stamper.close(); if (reader != null) reader.close(); reader = new PdfReader(new FileInputStream(template)); stamper = new PdfStamper(reader, new FileOutputStream( new File(filenameBegin + String.format("%02d", counterFile) + filenameEnd))); acroFields = stamper.getAcroFields(); counterSpells = 1; counterFile++; } acroFields.setField("Discipline" + counterSpells, disciplineNames.get(spelllistnr)); acroFields.setField("Spell Name" + counterSpells, spell.getName()); acroFields.setField("Spell Circle" + counterSpells, String.valueOf(spell.getCircle())); acroFields.setField("Spellcasting" + counterSpells, spell.getCastingdifficulty()); acroFields.setField("Threads" + counterSpells, spell.getThreads()); acroFields.setField("Weaving" + counterSpells, spell.getWeavingdifficulty()); acroFields.setField("Reattuning" + counterSpells, String.valueOf(spell.getReattuningdifficulty())); acroFields.setField("Range" + counterSpells, spell.getRange()); acroFields.setField("Duration" + counterSpells, spell.getDuration()); acroFields.setField("Effect" + counterSpells, spell.getEffect()); acroFields.setField("Page reference" + counterSpells, String.valueOf(spell.getBookref())); acroFields.setField("Air" + counterSpells, "No"); acroFields.setField("Earth" + counterSpells, "No"); acroFields.setField("Fear" + counterSpells, "No"); acroFields.setField("Fire" + counterSpells, "No"); acroFields.setField("Illusion" + counterSpells, "No"); acroFields.setField("Illusion N" + counterSpells, "Yes"); acroFields.setField("Water" + counterSpells, "No"); acroFields.setField("Wood" + counterSpells, "No"); switch (spell.getElement()) { case AIR: acroFields.setField("Air" + counterSpells, "Yes"); break; case EARTH: acroFields.setField("Earth" + counterSpells, "Yes"); break; case FEAR: acroFields.setField("Fear" + counterSpells, "Yes"); break; case FIRE: acroFields.setField("Fire" + counterSpells, "Yes"); break; case ILLUSION: acroFields.setField("Illusion" + counterSpells, "Yes"); acroFields.setField("Illusion N" + counterSpells, "No"); break; case WATER: acroFields.setField("Water" + counterSpells, "Yes"); break; case WOOD: acroFields.setField("Wood" + counterSpells, "Yes"); break; case UNDEFINED: break; } SpelldescriptionType spelldescription = spelldescriptions.get(spell.getName()); if ((spelldescription == null) || (spelldescription.getValue() == null)) acroFields.setField("Spell description" + counterSpells, ""); else acroFields.setField("Spell description" + counterSpells, spelldescription.getValue()); } spelllistnr++; } stamper.close(); }
From source file:de.mat.utils.pdftools.PdfAddPageNum.java
License:Mozilla Public License
/** * <h4>FeatureDomain:</h4>//ww w .j av a2 s. c om * PublishingTools * <h4>FeatureDescription:</h4> * read srcFile, adds pagenum and writes pages to destFile * <h4>FeatureResult:</h4> * <ul> * <li>creates destFile - output to destFile * </ul> * <h4>FeatureKeywords:</h4> * PDF Publishing * @param srcFile - source-file * @param destFile - destination-file * @param pageOffset - offset added to pagenumber * @throws Exception */ public void addPageNumber(String srcFile, String destFile, int pageOffset) throws Exception { PdfReader reader = null; PdfStamper stamper = null; try { // open files reader = new PdfReader(srcFile); stamper = new PdfStamper(reader, new FileOutputStream(destFile)); // add pagenum addPageNumber(reader, stamper, pageOffset); } catch (Exception ex) { // return Exception throw new Exception(ex); } finally { //close everything if (stamper != null) { stamper.close(); } if (reader != null) { reader.close(); } } }
From source file:de.mat.utils.pdftools.PdfSort4Print.java
License:Mozilla Public License
public static void sortPdfPages(String pdfSourceFile, String pdfDestinationFile, int perPage) throws Exception { PdfImportedPage page = null;// w w w. java 2 s.c o m if (perPage != 2 && perPage != 4) { throw new IllegalArgumentException( "Sorry, perPage must only be " + "2 or 4. All other is not implemented yet :-("); } // ####### // # fill to odd pagecount // ####### // create reader PdfReader readerOrig = new PdfReader(pdfSourceFile); // calc data int countPage = readerOrig.getNumberOfPages(); int blaetter = new Double(Math.ceil((countPage + 0.0) / perPage / 2)).intValue(); int zielPages = (blaetter * perPage * 2) - countPage; if (LOGGER.isInfoEnabled()) LOGGER.info("CurPages: " + countPage + " Blaetter:" + blaetter + " AddPage:" + zielPages); // add sites String oddFile = pdfDestinationFile + ".filled.pdf"; PdfStamper stamper = new PdfStamper(readerOrig, new FileOutputStream(oddFile)); // add empty pages for (int i = 1; i <= zielPages; i++) { if (LOGGER.isDebugEnabled()) LOGGER.debug("addEmptyPage: " + i); stamper.insertPage(readerOrig.getNumberOfPages() + 1, readerOrig.getPageSizeWithRotation(1)); } stamper.close(); readerOrig.close(); // ######## // # read new odd document and sort pages // ######## // step 1: create new reader PdfReader readerOdd = new PdfReader(oddFile); // create writerSorted String sortedFile = pdfDestinationFile; Document documentSorted = new Document(readerOrig.getPageSizeWithRotation(1)); PdfCopy writerSorted = new PdfCopy(documentSorted, new FileOutputStream(sortedFile)); documentSorted.open(); // add pages in calced order List<Integer> lstPageNr = new ArrayList<Integer>(); int pageCount = readerOdd.getNumberOfPages(); int startseite = 1; for (int i = 1; i <= blaetter; i++) { if (perPage == 2) { startseite = ((i - 1) * perPage) + 1; if (LOGGER.isDebugEnabled()) LOGGER.debug("Blatt:" + i + " Startseite: " + startseite); // front top lstPageNr.add(new Integer(pageCount - startseite + 1)); // front bottom lstPageNr.add(new Integer(startseite)); // back top lstPageNr.add(new Integer(startseite + 1)); // back bottom lstPageNr.add(new Integer(pageCount - startseite + 1 - 1)); } else if (perPage == 4) { startseite = ((i - 1) * perPage) + 1; if (LOGGER.isDebugEnabled()) LOGGER.debug("Blatt:" + i + " Startseite: " + startseite); // front top left lstPageNr.add(new Integer(pageCount - startseite + 1)); // front top right lstPageNr.add(new Integer(startseite)); // front bottom lefts lstPageNr.add(new Integer(pageCount - startseite + 1 - 2)); // front bottom right lstPageNr.add(new Integer(startseite + 2)); // back top left lstPageNr.add(new Integer(startseite + 1)); // back top right lstPageNr.add(new Integer(pageCount - startseite + 1 - 1)); // back bottom left lstPageNr.add(new Integer(startseite + 1 + 2)); // back bottom right lstPageNr.add(new Integer(pageCount - startseite + 1 - 1 - 2)); } else { throw new IllegalArgumentException( "Sorry, perPage must " + "only be 2 or 4. All other is not implemented yet :-("); } } if (LOGGER.isInfoEnabled()) LOGGER.info("Seiten:" + lstPageNr.size()); // copy pages for (Iterator iter = lstPageNr.iterator(); iter.hasNext();) { int pageNum = ((Integer) iter.next()).intValue(); if (LOGGER.isDebugEnabled()) LOGGER.debug("addSortPage: " + pageNum); page = writerSorted.getImportedPage(readerOdd, pageNum); writerSorted.addPage(page); } // close everything documentSorted.close(); writerSorted.close(); readerOdd.close(); // delete Tmp-File File file = new File(oddFile); file.delete(); }
From source file:dk.dma.epd.common.util.FALPDFGenerator.java
License:Apache License
public void generateFal1Form(FALForm1 fal1form, String filename) { try {/*from w ww . j av a 2 s . c om*/ PdfReader pdfReader = new PdfReader("FALForm1.pdf"); FileOutputStream fileWriteStream = new FileOutputStream(filename); PdfStamper pdfStamper = new PdfStamper(pdfReader, fileWriteStream); for (int i = 1; i <= pdfReader.getNumberOfPages(); i++) { PdfContentByte content = pdfStamper.getUnderContent(i); // Text over the existing page BaseFont bf = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.WINANSI, BaseFont.EMBEDDED); content.beginText(); content.setFontAndSize(bf, 8); int xFirstColum = 68; int xSecondColum = 314; int startYFirstColumn = 659; int startYSecondColumn = 659; // Arrival Depature if (fal1form.isArrival()) { content.showTextAligned(PdfContentByte.ALIGN_LEFT, "X", 316, 690, 0); } else { // Departure content.showTextAligned(PdfContentByte.ALIGN_LEFT, "X", 380, 690, 0); } // Name and Type of ship content.showTextAligned(PdfContentByte.ALIGN_LEFT, fal1form.getNameAndTypeOfShip(), xFirstColum, startYFirstColumn, 0); // IMO Number content.showTextAligned(PdfContentByte.ALIGN_LEFT, fal1form.getImoNumber(), xSecondColum, startYSecondColumn, 0); // Call Sign content.showTextAligned(PdfContentByte.ALIGN_LEFT, fal1form.getCallSign(), xFirstColum, startYFirstColumn - 30, 0); // Voyage Number content.showTextAligned(PdfContentByte.ALIGN_LEFT, fal1form.getVoyageNumber(), xSecondColum, startYSecondColumn - 30, 0); // Port of Arrival/depature content.showTextAligned(PdfContentByte.ALIGN_LEFT, fal1form.getPortOfArrivalDeapture(), xFirstColum, startYFirstColumn - 60, 0); // Date and time of arrival/depature content.showTextAligned(PdfContentByte.ALIGN_LEFT, fal1form.getDateAndTimeOfArrivalDepature(), xSecondColum, startYFirstColumn - 60, 0); // Flag State of ship content.showTextAligned(PdfContentByte.ALIGN_LEFT, fal1form.getFlagStateOfShip(), xFirstColum, startYFirstColumn - 90, 0); // Name of Master content.showTextAligned(PdfContentByte.ALIGN_LEFT, fal1form.getNameOfMaster(), xFirstColum + 135, startYFirstColumn - 90, 0); // Last port of call/next port of all content.showTextAligned(PdfContentByte.ALIGN_LEFT, fal1form.getLastPortOfCall(), xSecondColum, startYFirstColumn - 90, 0); // Certificate of registry content.showTextAligned(PdfContentByte.ALIGN_LEFT, fal1form.getCertificateOfRegistry(), xFirstColum, startYFirstColumn - 120, 0); String nameAndContact = fal1form.getNameAndContactDetalsOfShipsAgent(); addMultiLine(nameAndContact, startYFirstColumn, xSecondColum, content, 54, 120); // Gross Tonnage content.showTextAligned(PdfContentByte.ALIGN_LEFT, fal1form.getGrossTonnage(), xFirstColum, startYFirstColumn - 150, 0); // Net Tonnage content.showTextAligned(PdfContentByte.ALIGN_LEFT, fal1form.getNetTonnage(), xFirstColum + 135, startYFirstColumn - 150, 0); // Position of the ship in the port content.showTextAligned(PdfContentByte.ALIGN_LEFT, fal1form.getPositionOfTheShip(), xFirstColum, startYFirstColumn - 180, 0); // Brief particulars of voyage String briefVoyageParticulars = fal1form.getBriefParticulars(); addMultiLine(briefVoyageParticulars, startYFirstColumn, xFirstColum, content, 140, 210); // Brief particulars of cargo String briefCargoParticulars = fal1form.getBriefDescriptionOfCargo(); addMultiLine(briefCargoParticulars, startYFirstColumn, xFirstColum, content, 140, 257); // Number of Crew content.showTextAligned(PdfContentByte.ALIGN_LEFT, fal1form.getNumberOfCrew(), xFirstColum, startYFirstColumn - 305, 0); // Number of Passengers content.showTextAligned(PdfContentByte.ALIGN_LEFT, fal1form.getNumberOfPassengers(), xFirstColum + 130, startYFirstColumn - 305, 0); // Remarks String remarks = fal1form.getRemarks(); addMultiLine(remarks, startYFirstColumn, xSecondColum, content, 54, 305); // Ship waste requirements String wasteRequirements = fal1form.getShipWasteRequirements(); addMultiLine(wasteRequirements, startYFirstColumn, xSecondColum, content, 54, 405); content.endText(); } pdfStamper.close(); fileWriteStream.close(); fileWriteStream.flush(); } catch (IOException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } }
From source file:es.sm2.openppm.front.utils.DocumentUtils.java
License:Open Source License
/** * Create PDF for Control Change//w ww . jav a2 s . co m * @param idioma * @param project * @param change * @param preparedBy * @return * @throws DocumentException * @throws LogicException */ public static byte[] toPdf(ResourceBundle idioma, Project project, Changecontrol change, Employee preparedBy, final Image headerImg, final Image footerImg) throws DocumentException, LogicException { if (change == null) { throw new DocumentException("No change control found."); } if (preparedBy == null || preparedBy.getContact() == null) { throw new UserSendingException(); } Document document = new Document(PageSize.A4); document.setMargins(70F, 70F, 38F, 38F); // Total Height: 842pt, Total Width: 595pt byte[] file = null; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); @SuppressWarnings("unused") PdfWriter pdfWriter = PdfWriter.getInstance(document, outputStream); document.open(); Font fontHeader = new Font(FontFamily.TIMES_ROMAN, 9, Font.BOLD); Font fontCell = new Font(FontFamily.TIMES_ROMAN, 9); Font tituloFont = new Font(FontFamily.TIMES_ROMAN, 16, Font.BOLD); document.add(new Paragraph(" ", tituloFont)); document.add(new Paragraph(" ", tituloFont)); document.add(new Paragraph(" ", fontHeader)); Paragraph title = new Paragraph(idioma.getString("change_request").toUpperCase(), tituloFont); title.setAlignment(Paragraph.ALIGN_CENTER); document.add(title); // Header Table // Project info PdfPTable tableHeader = new PdfPTable(3); tableHeader.setWidthPercentage(100); tableHeader.setSpacingBefore(10); tableHeader.setSpacingAfter(15); int[] colWidth = new int[3]; colWidth[0] = 40; colWidth[1] = 30; colWidth[2] = 30; tableHeader.setWidths(colWidth); tableHeader.addCell( prepareHeaderCell(idioma.getString("change_request.project_name"), fontHeader, 1F, 0F, 0F, 1F)); tableHeader.addCell( prepareHeaderCell(idioma.getString("change_request.prepared_by"), fontHeader, 1F, 0F, 0F, 1F)); tableHeader.addCell(prepareHeaderCell(idioma.getString("change_request.date"), fontHeader, 1F, 1F, 0F, 1F)); tableHeader.addCell(prepareCell(project.getProjectName() + " / " + project.getAccountingCode(), fontCell, 0F, 0F, 0F, 1F)); tableHeader.addCell(prepareCell(preparedBy.getContact().getFullName(), fontCell, 0F, 0F, 0F, 1F)); tableHeader.addCell(prepareCell(DateUtil.format(idioma, new Date()), fontCell, 0F, 1F, 0F, 1F)); tableHeader.addCell( prepareHeaderCell(idioma.getString("change_request.customer"), fontHeader, 1F, 0F, 0F, 1F)); tableHeader.addCell( prepareHeaderCell(idioma.getString("change_request.contact_name"), fontHeader, 1F, 0F, 0F, 1F)); tableHeader.addCell( prepareHeaderCell(idioma.getString("change_request.customer_type"), fontHeader, 1F, 1F, 0F, 1F)); tableHeader.addCell(prepareCell(project.getCustomer() != null ? project.getCustomer().getName() : "", fontCell, 0F, 0F, 0F, 1F)); tableHeader.addCell(prepareCell((project.getCustomer() != null ? project.getCustomer().getName() : "-"), fontCell, 0F, 0F, 0F, 1F)); Customertype cusType = (project.getCustomer() != null ? project.getCustomer().getCustomertype() : null); tableHeader.addCell(prepareCell(cusType == null ? "" : cusType.getName(), fontCell, 0F, 1F, 0F, 1F)); tableHeader.addCell( prepareHeaderCell(idioma.getString("change_request.business_manager"), fontHeader, 1F, 0F, 0F, 1F)); tableHeader.addCell( prepareHeaderCell(idioma.getString("change_request.project_manager"), fontHeader, 1F, 0F, 0F, 1F)); tableHeader.addCell( prepareHeaderCell(idioma.getString("change_request.originator"), fontHeader, 1F, 1F, 0F, 1F)); Employee bm = project.getEmployeeByFunctionalManager(); Employee pm = project.getEmployeeByProjectManager(); tableHeader.addCell(prepareCell(bm == null ? "" : bm.getContact().getFullName(), fontCell, 0F, 0F, 1F, 1F)); tableHeader.addCell(prepareCell(pm == null ? "" : pm.getContact().getFullName(), fontCell, 0F, 0F, 1F, 1F)); tableHeader.addCell(prepareCell(change.getOriginator(), fontCell, 0F, 1F, 1F, 1F)); document.add(tableHeader); // Change Information document.add(new Paragraph(idioma.getString("change_information"))); PdfPTable tableInfo = new PdfPTable(1); tableInfo.setWidthPercentage(100); tableInfo.setSpacingBefore(10); tableInfo.setSpacingAfter(15); tableInfo.addCell(prepareHeaderCell(idioma.getString("change.change_type"), fontHeader, 1F, 1F, 0F, 1F)); tableInfo.addCell(prepareCell(change.getChangetype().getDescription(), fontCell, 0F, 1F, 0F, 1F)); String priorityDesc = ""; if (change.getPriority().equals('H')) priorityDesc = idioma.getString("change.priority.high"); if (change.getPriority().equals('N')) priorityDesc = idioma.getString("change.priority.normal"); if (change.getPriority().equals('L')) priorityDesc = idioma.getString("change.priority.low"); tableInfo.addCell(prepareHeaderCell(idioma.getString("change.priority"), fontHeader, 1F, 1F, 0F, 1F)); tableInfo.addCell(prepareCell(priorityDesc, fontCell, 0F, 1F, 0F, 1F)); tableInfo.addCell(prepareHeaderCell(idioma.getString("change.desc"), fontHeader, 1F, 1F, 0F, 1F)); tableInfo.addCell(prepareCell(change.getDescription(), fontCell, 0F, 1F, 0F, 1F)); tableInfo.addCell( prepareHeaderCell(idioma.getString("change.recommended_solution"), fontHeader, 1F, 1F, 0F, 1F)); tableInfo.addCell(prepareCell(change.getRecommendedSolution(), fontCell, 0F, 1F, 1F, 1F)); PdfPTable tableSubInfo = new PdfPTable(3); tableSubInfo.setWidthPercentage(100); //TODO MIGRACION tableSubInfo.addCell(prepareSubCell(idioma.getString("change.wbs_node"), fontHeader)); tableSubInfo.addCell(prepareSubCell(idioma.getString("change.estimated_effort"), fontHeader)); tableSubInfo.addCell(prepareSubCell(idioma.getString("change.estimated_cost"), fontHeader)); tableSubInfo.addCell( prepareSubCell((change.getWbsnode() != null ? change.getWbsnode().getName() : ""), fontCell)); tableSubInfo.addCell(prepareSubCell( (change.getEstimatedEffort() != null ? String.valueOf(change.getEstimatedEffort()) : ""), fontCell)); tableSubInfo.addCell(prepareSubCell( (change.getEstimatedCost() != null ? ValidateUtil.toCurrency(change.getEstimatedCost()) : ""), fontCell)); PdfPCell subTable = new PdfPCell(tableSubInfo); subTable.setBorderWidth(1F); tableInfo.addCell(subTable); tableInfo.addCell(prepareHeaderCell(idioma.getString("change.impact_desc"), fontHeader, 1F, 1F, 0F, 1F)); tableInfo.addCell(prepareCell(change.getImpactDescription(), fontCell, 0F, 1F, 1F, 1F)); document.add(tableInfo); document.add(new Paragraph(idioma.getString("change.resolution"))); PdfPTable tableResolution = new PdfPTable(1); tableResolution.setWidthPercentage(100); tableResolution.setSpacingBefore(10); tableResolution.setSpacingAfter(15); tableResolution .addCell(prepareHeaderCell(idioma.getString("change.resolution"), fontHeader, 1F, 1F, 0F, 1F)); tableResolution.addCell( prepareCell((change.getResolution() != null && change.getResolution() ? idioma.getString("yes") : idioma.getString("no")), fontCell, 0F, 1F, 0F, 1F)); tableResolution .addCell(prepareHeaderCell(idioma.getString("change.resolution_date"), fontHeader, 1F, 1F, 0F, 1F)); tableResolution.addCell( prepareCell(DateUtil.format(idioma, change.getResolutionDate()), fontCell, 0F, 1F, 0F, 1F)); tableResolution.addCell( prepareHeaderCell(idioma.getString("change.resolution_reason"), fontHeader, 1F, 1F, 0F, 1F)); tableResolution.addCell(prepareCell(change.getResolutionReason(), fontCell, 0F, 1F, 1F, 1F)); document.add(tableResolution); document.close(); try { PdfReader reader = new PdfReader(outputStream.toByteArray()); PdfStamper stamper = new PdfStamper(reader, outputStream); int numPag = reader.getNumberOfPages(); for (int i = 1; i <= reader.getNumberOfPages(); i++) { setHeaderFooter(i, numPag, headerImg, footerImg, reader, stamper, idioma); } stamper.close(); } catch (IOException e) { e.printStackTrace(); } file = outputStream.toByteArray(); return file; }
From source file:ExternalForms.Browser.java
public String getDataFromPDF() { String all_inputs = ""; //concatenated string of inputs in order try {// ww w .j a v a2 s . c om final int MAX_VARIABLES = connect.getFormVarCount(formID); //get from db System.out.println("MAX VARIABLES: " + MAX_VARIABLES); //---------------------------------------------------------- final String DELIMITER = "~"; //pwede mani i-change dumbNavigate(); PdfReader pdfTemplate = new PdfReader(documentsPath + "\\" + formName + ".pdf"); FileOutputStream fileOutputStream = new FileOutputStream( dirPrintables.getAbsolutePath() + "\\" + formName + ".pdf"); PdfStamper stamper = new PdfStamper(pdfTemplate, fileOutputStream); //System.out.println("TRY: " + stamper.getAcroFields().getField("1")); stamper.setFormFlattening(true); System.out.println("Display Inputs Per Variable and Concatenate after\n"); //change textFields-------------------------------------------------------------------- for (int var = 1; var <= MAX_VARIABLES; var++) { String input_from_pdf_field = stamper.getAcroFields().getField("" + var); //get field input using variable System.out.println("Input #" + var + " = " + input_from_pdf_field); //display all_inputs += DELIMITER + input_from_pdf_field; //concatenate } stamper.close(); pdfTemplate.close(); //-------------------------------------------------------------------------------------- System.out.println("\nConcatenated String to Store to DB\n"); System.out.println("\n" + all_inputs + "\n"); try { File pdfFile = new File(documentsPath + "\\" + formName + ".pdf"); if (pdfFile.exists()) { if (pdfFile.delete()) { //Desktop.getDesktop().open(pdfFile); System.out.println("Form in Documents Deleted"); } } else { System.out.println("File to delete in My Documents does not exists!"); } } catch (Exception ex) { } b.setVisible(false); c.setText("Done"); j.navigate(dirPrintables.getAbsolutePath() + "\\" + formName + ".pdf"); System.out.println(dirPrintables.getAbsolutePath() + "\\" + formName + ".pdf"); } catch (IOException | DocumentException ex) { Logger.getLogger(Browser.class.getName()).log(Level.SEVERE, null, ex); } return all_inputs; }
From source file:ExternalForms.Browser.java
public void setDataToPdf(String fName, String formEntryID) { try {//w w w. ja va2 s.com String all_inputs = connect.getFormEntryFormData(formEntryID); //assuming na gusto ka magbutang ug tulo ka value sa first 3 fields final String DELIMITER = "~"; System.out.println("\nSplit Concatenated String and Display\n"); String split_inputs[] = all_inputs.split(DELIMITER); PdfReader pdfTemplate = new PdfReader( dirTemplates.getAbsolutePath() + "\\" + (formName = fName) + ".pdf"); //navigate("temp", "x"); postFix = checkIfSameNameFileExists(this.dirPrintables, formName + ".pdf"); System.out.println("FILENAME TO FETCH: " + formName + postFix + "|"); FileOutputStream fileOutputStream = new FileOutputStream( dirPrintables.getAbsolutePath() + "\\" + formName + postFix + ".pdf"); PdfStamper stamper = new PdfStamper(pdfTemplate, fileOutputStream); stamper.setFormFlattening(true); //change textFields-------------------------------------------------------------------- for (int var = 1; var < split_inputs.length; var++) { stamper.getAcroFields().setField("" + var, split_inputs[var]); //get field input using variable System.out.println("Input #" + var + " = " + split_inputs[var]); //display } //-------------------------------------------------------------------------------------- stamper.close(); pdfTemplate.close(); b.setVisible(false); c.setText("Done"); j.navigate(dirPrintables.getAbsolutePath() + "\\" + formName + postFix + ".pdf"); this.setVisible(true); System.out.println(dirPrintables.getAbsolutePath() + "\\" + formName + postFix + ".pdf"); } catch (IOException | DocumentException ex) { Logger.getLogger(Browser.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:ExternalNonFormClasses.RequestFormBrowser.java
public void disableFormOnly(boolean choice) { //save data try {//w w w . j a va 2s . co m PdfReader pdfTemplate = new PdfReader( "C:\\Users\\mrRNBean\\Documents\\NetBeansProjects\\BRMS_V2\\build\\templates\\" + form_name + ".pdf"); FileOutputStream fileOutputStream = new FileOutputStream( "C:\\Users\\mrRNBean\\Documents\\NetBeansProjects\\BRMS_V2\\build\\printables\\" + form_name + ".pdf"); PdfStamper stamper = new PdfStamper(pdfTemplate, fileOutputStream); stamper.setFormFlattening(true); if (choice) { //post-request //manipiulate form fields-------------------------------------------------------------------- stamper.getAcroFields().setField("12", "CHORVES"); //String x = stamper.getAcroFields().getField("province"); //------------------------------------------------------------------------------------------- //get field form_vars from form tb //slice data with delimiter and store to array //fetch array //use as basis for loop //get field using variable name in each array entry //every field entry should be added to a string concatenation //save string concatenation and form in "printables/" to FormRequest.tb } stamper.close(); pdfTemplate.close(); } catch (IOException | DocumentException ex) { Logger.getLogger(RequestFormBrowser.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:fattura.Fattura.java
public void setFattura(String cliente, String data, AtomicInteger numerofattura, PdfStamper s) throws SQLException, DocumentException, FileNotFoundException, IOException { //Ho messo che il numero della fattura va passato come parametro, voglio capire se si pu fare altrimenti (con un contatore) try {//from ww w . j av a2 s . c o m s.getAcroFields().setField("Num", numerofattura.toString()); // sistemare s.getAcroFields().setField("Data", data); s.getAcroFields().setField("Nome", cliente); PdfContentByte content = s.getUnderContent(1);//1 for the first page BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.EMBEDDED); content.beginText(); content.setFontAndSize(bf, 7); inserisciDatiMaglie(cliente, data, s); inserisciDatiBorse(cliente, data, s); inserisciDatiPanta(cliente, data, s); inserisciDatiGiubb(cliente, data, s); inserisciDatiFelpe(cliente, data, s); inserisciDatiPubb(cliente, data, s); setImporti(s); content.endText(); s.close(); } catch (IOException | DocumentException e) { } }