Following is a demo code to generate a PDF doc from a HTML source:
public class SimpleAdhocReport
{
public SimpleAdhocReport()
{
build();
}
private void build()
{
AdhocConfiguration configuration = new AdhocConfiguration();
AdhocReport report = new AdhocReport();
configuration.setReport(report);
AdhocColumn column = new AdhocColumn();
column.setName("item");
report.addColumn(column);
column = new AdhocColumn();
column.setName("orderdate");
report.addColumn(column);
column = new AdhocColumn();
column.setName("quantity");
report.addColumn(column);
column = new AdhocColumn();
column.setName("unitprice");
report.addColumn(column);
try
{
AdhocManager.saveConfiguration(configuration, new FileOutputStream("d:/configuration.xml"));
#SuppressWarnings("unused")
AdhocConfiguration loadedConfiguration = AdhocManager.loadConfiguration(new FileInputStream("d:/configuration.xml"));
JasperReportBuilder reportBuilder = AdhocManager.createReport(configuration.getReport());
reportBuilder.setDataSource(createDataSource());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
reportBuilder.toHtml(baos);
String html = new String(baos.toByteArray(), "UTF-8");
baos.close();
Whitelist wl = Whitelist.simpleText();
wl.addTags("table", "tr", "td");
String clean = Jsoup.clean(html, wl);
clean = clean.replace("<td></td>", "");
clean = clean.replace("<td> </td>", "");
clean = clean.replace("<td> ", "<td>");
Document doc = Jsoup.parse(clean);
for (Element element : doc.select("*"))
{
if (!element.hasText() && element.isBlock())
{
element.remove();
}
}
clean = doc.body().html();
int startIndex = clean.indexOf("<table>", 6);
int endIndex = clean.indexOf("</table>");
clean = clean.substring(startIndex, endIndex + 8);
BufferedWriter writer = new BufferedWriter(new FileWriter(("d:/test.html")));
writer.write(clean);
writer.close();
try
{
createPdf(clean);
}
catch (DocumentException e)
{
e.printStackTrace();
}
}
catch (DRException e)
{
e.printStackTrace();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private JRDataSource createDataSource()
{
DRDataSource dataSource = new DRDataSource("item", "orderdate", "quantity", "unitprice");
for (int i = 0; i < 20; i++)
{
dataSource.add("Book", new Date(), (int) (Math.random() * 10) + 1,
new BigDecimal(Math.random() * 100 + 1).setScale(4, BigDecimal.ROUND_HALF_UP));
}
return dataSource;
}
public static void main(String[] args)
{
new SimpleAdhocReport();
}
public void createPdf(String html) throws IOException, DocumentException
{
com.itextpdf.text.Document document = new com.itextpdf.text.Document(PageSize.LETTER);
document.setMargins(30, 30, 80, 30);
PdfWriter.getInstance(document, new FileOutputStream("D:\\HTMLtoPDF.pdf"));
document.open();
PdfPTable table = null;
ElementList list = com.itextpdf.tool.xml.XMLWorkerHelper.parseToElementList(html, null);
for (com.itextpdf.text.Element element : list)
{
table = new PdfPTable((PdfPTable) element);
}
table.setWidthPercentage(100);
ArrayList<PdfPRow> rows = table.getRows();
for (PdfPRow rw : rows)
{
PdfPCell[] cells = rw.getCells();
for (PdfPCell cl : cells)
{
cl.setVerticalAlignment(com.itextpdf.text.Element.ALIGN_MIDDLE);
cl.setBorder(PdfPCell.NO_BORDER);
cl.setNoWrap(true);
cl.setPadding(10f);
cl.setCellEvent(new MyCell());
}
}
document.add(table);
document.close();
}
}
class MyCell implements PdfPCellEvent
{
public void cellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvases)
{
float x1 = position.getLeft() - 2;
float x2 = position.getRight() + 2;
float y1 = position.getTop() + 2;
float y2 = position.getBottom() - 2;
PdfContentByte canvas = canvases[PdfPTable.LINECANVAS];
canvas.rectangle(x1, y1, x2 - x1, y2 - y1);
canvas.stroke();
}
}
I am working with jasper reports to create a adhoc report and generate the HTML from there. I have to generate a PDF from this HTML.
Couple of issue I am facing, any help is appreciated:
I am setting the
table.setWidthPercentage(100);
for a page with table its not working.
I have to increase spacing between columns. Tried what Bruno suggested here. Its not working. I have also tried using a solution from here with no luck. Ref. image below.
Also if i cell event to default is not working.
e.g.
table.getDefaultCell().setCellEvent()
Any suggestions ?
Update:
My Output
I was able to get the padding as i want by parsing the HTML following way:
public PdfPTable getTable(String cleanHTML) throws IOException
{
String CSS = "tr { text-align: center; } td { padding: 5px; }";
CSSResolver cssResolver = new StyleAttrCSSResolver();
CssFile cssFile = XMLWorkerHelper.getCSS(new ByteArrayInputStream(CSS.getBytes()));
cssResolver.addCss(cssFile);
// HTML
HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());
// Pipelines
ElementList elements = new ElementList();
ElementHandlerPipeline pdf = new ElementHandlerPipeline(elements, null);
HtmlPipeline html = new HtmlPipeline(htmlContext, pdf);
CssResolverPipeline css = new CssResolverPipeline(cssResolver, html);
// XML Worker
XMLWorker worker = new XMLWorker(css, true);
XMLParser p = new XMLParser(worker);
p.parse(new ByteArrayInputStream(cleanHTML.getBytes()));
return (PdfPTable) elements.get(0);
}
That fixes the issue mentioned in question 2. Q3 is not longer required.
Related
I'm working on PDF Toc. It generates the first page but when I have more elements I did logic to create a new page for TOC. I'm using PDF Box and that PDPageContentStream.
I had to create a function to calculate how many pages I need. Then I'm creating the exact amount of pages in the list and add them to the PDF document before I start PDPageContentStream. That stream is in a loop and it's only generating the first page. Other pages come blank. I don't know what exactly is wrong. Here is the code:
PDDocument pdf = new PDDocument();
int numberOfTocPages = calculateTocPages(50, tocStyle, _height, currentYPosition, leading);
List<PDPage> tocPages = new ArrayList<PDPage>();
for (int i = 0; i < numberOfTocPages; i++) {
PDPage toc = new PDPage(new PDRectangle(_width, _height));
tocPages.add(toc);
}
float numberingXPosition = _width - (contentMarginLeft + contentMarginRight) - 100;
int j = 0;
PDDocument temp = new PDDocument();
for (int i = 0; i < numberOfTocPages; i++) {
PDPage toc = tocPages.get(i);
pdf.addPage(toc);
try {
PDPageContentStream contentStream = new PDPageContentStream(pdf, toc, PDPageContentStream.AppendMode.APPEND, true, false);
contentStream.beginText();
if (i == 0) {
contentStream.setFont(font, fontSize);
contentStream.setNonStrokingColor(tocStyle.getHeaderFontColor());
contentStream.newLineAtOffset(headerMarginLeft, currentYPosition);
contentStream.showText(StylingEnums.TABLE_OF_CONTENTS);
}
fontSize = tocStyle.getContentFontSize();
leading = 1.5f * fontSize;
contentStream.setFont(PDType1Font.HELVETICA, fontSize);
contentStream.setNonStrokingColor(tocStyle.getContentFontColor());
contentStream.newLineAtOffset(contentMarginLeft, -leading);
currentYPosition -= leading;
contentStream.setLeading(leading);
// List<TocContentData> tocItems = _tocData.getTocItems();
while (j < 50) {
if (currentYPosition >= 2 * tocStyle.getContentMarginBottom()) {
// TocContentData item = tocItems.get(i);
contentStream.showText("Item " + j);
contentStream.newLineAtOffset(numberingXPosition, 0);
int pageNumber = j;
contentStream.showText(Integer.toString(pageNumber + 1));
contentStream.newLineAtOffset(-numberingXPosition, 0);
contentStream.newLine();
currentYPosition -= leading;
j++;
} else {
System.out.println("New page!!!");
currentYPosition = initialPosition;
break;
}
}
contentStream.endText();
contentStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
FileOutputStream out;
try {
out = new FileOutputStream(fileName + ".pdf");
pdf.save(out);
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Page 2 sets the Y offset with this code because currentYPosition is not used when i > 0
contentStream.newLineAtOffset(contentMarginLeft, -leading);
so your first Y offset value is negative.
I have a pdf document with one or more pages A4 paper.
The resulting pdf document should be A3 paper where each page contains two from the first one (odd on the left, even on the right side).
I already got it to render the A4 pages into images and the odd pages are successfully placed on the first parts of a new A3 pages but I cannot get the even pages to be placed.
public class CreateLandscapePDF {
public void renderPDF(File inputFile, String output) {
PDDocument docIn = null;
PDDocument docOut = null;
float width = 0;
float height = 0;
float posX = 0;
float posY = 0;
try {
docIn = PDDocument.load(inputFile);
PDFRenderer pdfRenderer = new PDFRenderer(docIn);
docOut = new PDDocument();
int pageCounter = 0;
for(PDPage pageIn : docIn.getPages()) {
pageIn.setRotation(270);
BufferedImage bufferedImage = pdfRenderer.renderImage(pageCounter);
width = bufferedImage.getHeight();
height = bufferedImage.getWidth();
PDPage pageOut = new PDPage(PDRectangle.A3);
PDImageXObject image = LosslessFactory.createFromImage(docOut, bufferedImage);
PDPageContentStream contentStream = new PDPageContentStream(docOut, pageOut, AppendMode.APPEND, true, true);
if((pageCounter & 1) == 0) {
pageOut.setRotation(90);
docOut.addPage(pageOut);
posX = 0;
posY = 0;
} else {
posX = 0;
posY = width;
}
contentStream.drawImage(image, posX, posY);
contentStream.close();
bufferedImage.flush();
pageCounter++;
}
docOut.save(output + "\\LandscapeTest.pdf");
docOut.close();
docIn.close();
} catch(IOException io) {
io.printStackTrace();
}
}
}
I'm using Apache PDFBox 2.0.2 (pdfbox-app-2.0.2.jar)
Thank you very much for your help and the link to the other question - I think I already read it but wasn't able to use in in my code yet.
But finally the PDFClown made the job, though I think it's not very nice to use PDFBox and PDFClown in the same program.
Anyway here's my working code to combine A4 pages on A3 paper.
public class CombinePages {
public void run(String input, String output) {
try {
Document source = new File(input).getDocument();
Pages sourcePages = source.getPages();
Document target = new File().getDocument();
Page targetPage = null;
int pageCounter = 0;
double moveByX = .0;
for(Page sourcePage : source.getPages()) {
if((pageCounter & 1) == 0) {
//even page gets a blank page
targetPage = new Page(target);
target.setPageSize(PageFormat.getSize(PageFormat.SizeEnum.A3, PageFormat.OrientationEnum.Landscape));
target.getPages().add(targetPage);
moveByX = .0;
} else {
moveByX = .50;
}
//get content from source page
XObject xObject = sourcePages.get(pageCounter).toXObject(target);
PrimitiveComposer composer = new PrimitiveComposer(targetPage);
Dimension2D targetSize = targetPage.getSize();
Dimension2D sourceSize = xObject.getSize();
composer.showXObject(xObject, new Point2D.Double(targetSize.getWidth() * moveByX, targetSize.getHeight() * .0), new Dimension(sourceSize.getWidth(), sourceSize.getHeight()), XAlignmentEnum.Left, YAlignmentEnum.Top, 0);
composer.flush();
pageCounter++;
}
target.getFile().save(output + "\\CombinePages.pdf", SerializationModeEnum.Standard);
source.getFile().close();
} catch (FileNotFoundException fnf) {
log.error(fnf);
} catch (IOException io) {
log.error(io);
}
}
}
I need to create multiple excel sheet in Java using jExcel API if one sheet is full (65536 rows). Suppose if one sheet got full then in the next sheet it should start writing automatically from where it left off in the first sheet. I am just stuck on putting the logic to create it dynamically whenever one sheet is full. Below is the code that I have done so far.
public void write() throws IOException, WriteException {
File file = new File(inputFile);
WorkbookSettings wbSettings = new WorkbookSettings();
wbSettings.setLocale(new Locale("en", "EN"));
WritableWorkbook workbook = Workbook.createWorkbook(file, wbSettings);
writingToExcel(workbook);
}
//Logic to create sheet dyanmically if one is full should be done here I guess?
private void writingToExcel(WritableWorkbook workbook) {
workbook.createSheet("Report", 0);
WritableSheet excelSheet = workbook.getSheet(0);
try {
createLabel(excelSheet);
createContent(excelSheet);
} catch (WriteException e) {
e.printStackTrace();
} finally {
try {
workbook.write();
workbook.close();
} catch (IOException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
}
}
private void createLabel(WritableSheet sheet) throws WriteException {
WritableFont times10pt = new WritableFont(WritableFont.TIMES, 10);
times = new WritableCellFormat(times10pt);
times.setWrap(true);
WritableFont times10ptBoldUnderline = new WritableFont(WritableFont.TIMES, 10, WritableFont.BOLD, false,UnderlineStyle.SINGLE);
timesBoldUnderline = new WritableCellFormat(times10ptBoldUnderline);
timesBoldUnderline.setWrap(true);
CellView cv = new CellView();
cv.setFormat(times);
cv.setFormat(timesBoldUnderline);
cv.setAutosize(true);
// Write a few headers
addCaption(sheet, 0, 0, "Header 1");
addCaption(sheet, 1, 0, "This is another header");
}
private void createContent(WritableSheet sheet) throws WriteException,
RowsExceededException {
for (int i = 1; i < 70000; i++) {
addNumber(sheet, 0, i, i + 10);
addNumber(sheet, 1, i, i * i);
}
}
private void addCaption(WritableSheet sheet, int column, int row, String s)
throws RowsExceededException, WriteException {
Label label;
label = new Label(column, row, s, timesBoldUnderline);
sheet.addCell(label);
}
private void addNumber(WritableSheet sheet, int column, int row,
Integer integer) throws WriteException, RowsExceededException {
Number number;
number = new Number(column, row, integer, times);
sheet.addCell(number);
}
I am not sure how to add that logic here in my code.
Any suggestions will be of great help?
Or in any case, can anyone provide me a simple example in which if one sheet is full, it should start writing automatically into different sheet (Second sheet)?
I made changes to the following 2 methods:-
private void writingToExcel(WritableWorkbook workbook) {
try {
// don't create a sheet now, instead, pass it in the workbook
createContent(workbook);
}
catch (WriteException e) {
e.printStackTrace();
}
finally {
try {
workbook.write();
workbook.close();
}
catch (IOException e) {
e.printStackTrace();
}
catch (WriteException e) {
e.printStackTrace();
}
}
}
// instead of taking a sheet, take a workbook because we cannot ensure if the sheet can fit all the content at this point
private void createContent(WritableWorkbook workbook) throws WriteException {
int excelSheetIndex = 0;
int rowIndex = 0;
WritableSheet excelSheet = null;
for (int i = 1; i < 70000; i++) {
// if the sheet has hit the cap, then create a new sheet, new label row and reset the row count
if (excelSheet == null || excelSheet.getRows() == 65536) {
excelSheet = workbook.createSheet("Report " + excelSheetIndex, excelSheetIndex++);
createLabel(excelSheet);
rowIndex = 0;
}
// instead of using i for row, use rowIndex
addNumber(excelSheet, 0, rowIndex, i + 10);
addNumber(excelSheet, 1, rowIndex, i * i);
// increment the sheet row
rowIndex++;
}
}
public class DscMigration {
private WritableCellFormat timesBoldUnderline;
private WritableCellFormat times;
private String inputFile;
public void setOutputFile(String inputFile) {
this.inputFile = inputFile;
}
public void write() throws IOException, WriteException {
File file = new File(inputFile);
WorkbookSettings wbSettings = new WorkbookSettings();
wbSettings.setLocale(new Locale("en", "EN"));
WritableWorkbook workbook = Workbook.createWorkbook(file, wbSettings);
workbook.createSheet("Report", 0);
WritableSheet excelSheet = workbook.getSheet(0);
createLabel(excelSheet);
createContent(excelSheet);
workbook.write();
workbook.close();
}
private void createLabel(WritableSheet sheet) throws WriteException {
// Lets create a times font
WritableFont times10pt = new WritableFont(WritableFont.TIMES, 10);
// Define the cell format
times = new WritableCellFormat(times10pt);
// Lets automatically wrap the cells
times.setWrap(true);
// Create create a bold font with unterlines
WritableFont times10ptBoldUnderline = new WritableFont(
WritableFont.TIMES, 10, WritableFont.BOLD, false,
UnderlineStyle.SINGLE);
timesBoldUnderline = new WritableCellFormat(times10ptBoldUnderline);
// Lets automatically wrap the cells
timesBoldUnderline.setWrap(true);
CellView cv = new CellView();
cv.setFormat(times);
// cv.setFormat(timesBoldUnderline);
// cv.setFormat(cf)
cv.setAutosize(true);
// Write a few headers
addCaption(sheet, 0, 0, "COM_ID");
addCaption(sheet, 1, 0, "OBJECTID");
addCaption(sheet, 2, 0, "GNOSISID");
}
private void createContent(WritableSheet sheet) throws WriteException,
RowsExceededException {
/**
* Create a new instance for cellDataList
*/
List<DataObj> cellDataListA = new ArrayList<DataObj>();
List<DataObj> nonDuplicateA = new ArrayList<DataObj>();
List<DataObj2> cellDataListB = new ArrayList<DataObj2>();
List<DataObj2> nonDuplicateB = new ArrayList<DataObj2>();
List<DataObj> nonDuplicateAB = new ArrayList<DataObj>();
List<DataObj> misMatchAB = new ArrayList<DataObj>();
List<DataObj> copyA = new ArrayList<DataObj>();
List<DataObj2> comID = new ArrayList<DataObj2>();
try {
/**
* Create a new instance for FileInputStream class
*/
// input1--> col1 -livelink id ; col2->livlink filename; col3-> gnosis id; col4-> filename
FileInputStream fileInputStream = new FileInputStream(
"C:/Documents and Settings/nithya/Desktop/DSC/Report/input1.xls");
//input2 --> col1 comid all, col2 -> object id for common
FileInputStream fileInputStream2 = new FileInputStream(
"C:/Documents and Settings/nithya/Desktop/DSC/Report/input2.xls");
/**
* Create a new instance for POIFSFileSystem class
*/
POIFSFileSystem fsFileSystem = new POIFSFileSystem(fileInputStream);
POIFSFileSystem fsFileSystem2 = new POIFSFileSystem(fileInputStream2);
/*
* Create a new instance for HSSFWorkBook Class
*/
HSSFWorkbook workBook = new HSSFWorkbook(fsFileSystem);
HSSFSheet hssfSheet = workBook.getSheetAt(0);
HSSFWorkbook workBook2 = new HSSFWorkbook(fsFileSystem2);
HSSFSheet hssfSheet2 = workBook2.getSheetAt(0);
/**
* Iterate the rows and cells of the spreadsheet to get all the
* datas.
*/
Iterator rowIterator = hssfSheet.rowIterator();
Iterator rowIterator2 = hssfSheet2.rowIterator();
while (rowIterator.hasNext()) {
HSSFRow hssfRow = (HSSFRow) rowIterator.next();
if ((hssfRow.getCell((short) 0) != null)
&& (hssfRow.getCell((short) 1) != null)) {
cellDataListA.add(new DataObj(hssfRow.getCell((short) 0)
.toString().trim(), hssfRow.getCell((short) 1)
.toString().trim()));
}
if ((hssfRow.getCell((short) 2) != null)
&& (hssfRow.getCell((short) 3) != null)) {
cellDataListB.add(new DataObj2(hssfRow.getCell((short) 2)
.toString().trim(), hssfRow.getCell((short) 3)
.toString().trim()));
}
}
// Replace Duplicate in Livelink Startd
Set set = new HashSet();
List newList = new ArrayList();
nonDuplicateA.addAll(cellDataListA);
for (int i = 0; i < nonDuplicateA.size(); i++) {
DataObj b = nonDuplicateA.get(i);
if (set.add(b.getCol1()))
newList.add(nonDuplicateA.get(i));
}
nonDuplicateA.clear();
nonDuplicateA.addAll(newList);
for (int i = 0; i < nonDuplicateA.size(); i++) {
DataObj a = nonDuplicateA.get(i);
}
System.out.println("nonDuplicateA=="+nonDuplicateA.size());
// Replace Duplicate in Livelink End
// Replace Duplicate in Gnosis Startd
Set set2 = new HashSet();
List newList2 = new ArrayList();
System.out.println("cellDataListB=="+cellDataListB.size());
nonDuplicateB.addAll(cellDataListB);
for (int i = 0; i < nonDuplicateB.size(); i++) {
DataObj2 b = nonDuplicateB.get(i);
if (set2.add(b.getCol1()))
newList2.add(nonDuplicateB.get(i));
}
nonDuplicateB.clear();
nonDuplicateB.addAll(newList2);
System.out.println("nonDuplicateB=="+nonDuplicateB.size());
// Replace Duplicate in Gnosis End
// Common record
//System.out.println("------Common----");
for (int i = 0; i < nonDuplicateA.size(); i++) {
DataObj a = nonDuplicateA.get(i);
for (int j = 0; j < nonDuplicateB.size(); j++) {
DataObj2 b = nonDuplicateB.get(j);
if((a.getCol2()!=null && b.getCol2()!=null )){
//System.out.println("---------");
if (a.getCol2().equalsIgnoreCase(b.getCol2())) {
// System.out.println(a.getCol2() +"--"+i+"--"+b.getCol2());
nonDuplicateAB.add(new DataObj(a.getCol1().toString()
.trim(), b.getCol1().toString().trim()));
//addLabel(sheet, 0, i, a.getCol1().toString().trim());
// addLabel(sheet, 1, i, b.getCol1().toString().trim());
break;
}
}
}
}
System.out.println("nonDuplicateAB=="+nonDuplicateAB.size());
TreeMap misA = new TreeMap();
//System.out.println("------Missing----");
for (int i = 0; i < nonDuplicateA.size(); i++) {
DataObj a = nonDuplicateA.get(i);
for (int j = 0; j < nonDuplicateB.size(); j++) {
DataObj2 b = nonDuplicateB.get(j);
if((a.getCol2()!=null && b.getCol2()!=null )){
if (!(a.getCol2().equals(b.getCol2()))) {
//System.out.println(a.getCol1() +"="+b.getCol1());
//break;
if(misA.containsValue(a.getCol2())){
misA.remove(a.getCol1());
}
else
{
misA.put(a.getCol1(), a.getCol2());
}
}
}
}
}
//System.out.println("SIze mis="+misA);
TreeMap misB = new TreeMap();
for (int i = 0; i < nonDuplicateB.size(); i++) {
DataObj2 a = nonDuplicateB.get(i);
for (int j = 0; j < nonDuplicateA.size(); j++) {
DataObj b = nonDuplicateA.get(j);
if((a.getCol2()!=null && b.getCol2()!=null )){
if (!(a.getCol2().equals(b.getCol2()))) {
//System.out.println(a.getCol1() +"="+b.getCol1());
if(misB.containsValue(a.getCol2())){
misB.remove(a.getCol1());
}
else
{
misB.put(a.getCol1(), a.getCol2());
}
}
}
}
}
// System.out.println("SIze misB="+misB);
//Getting ComID and Object Id from excel start
while (rowIterator2.hasNext()) {
HSSFRow hssfRow2 = (HSSFRow) rowIterator2.next();
if ((hssfRow2.getCell((short) 0) != null)
&& (hssfRow2.getCell((short) 1) != null)) {
comID.add(new DataObj2(hssfRow2.getCell((short) 0)
.toString().trim(), hssfRow2.getCell((short) 1)
.toString().trim()));
}
}
System.out.println("Size ComID="+comID.size());
TreeMap hm = new TreeMap();
System.out.println("Please wait...Data comparison.. ");
for (int i = 0; i < nonDuplicateAB.size(); i++) {
DataObj a = nonDuplicateAB.get(i);
for(int j=0;j<comID.size();j++ ){
DataObj2 b = comID.get(j);
//System.out.println((b.getCol2()+"---"+a.getCol1()));
if(b.getCol2().equalsIgnoreCase(a.getCol1())){
hm.put(b.getCol1(), b.getCol2());
break;
}
}
}
System.out.println("Size HM="+hm.size());
//Getting ComID and Object Id from excel End
//Data Base Updation
Connection conn = null;
try {
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
conn = DriverManager.getConnection(
"jdbc:oracle:thin:#cxxxxx:5487:dev", "",
"");
System.out.println("after calling conn");
Set set6 = hm.entrySet();
Iterator i = set6.iterator();
String gnosisNodeId="";
int update=1;
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
//System.out.print(me.getKey() + ": ");
//System.out.println(me.getValue());
// System.out.println("nonDuplicateAB="+nonDuplicateAB.size());
for(int m=0;m<nonDuplicateAB.size();m++){
DataObj a = nonDuplicateAB.get(m);
if(me.getValue().toString().equalsIgnoreCase(a.getCol1())){
gnosisNodeId=a.getCol2().toString();
nonDuplicateAB.remove(m);
break;
}
}
//System.out.println("nonDuplicateAB="+nonDuplicateAB.size());
if(gnosisNodeId!=null){
//System.out.println("LOOP");
String s1="UPDATE component SET com_xml = UPDATEXML(com_xml, '*/url/value/text()', '";
String s2="http://dmfwebtop65.pfizer.com/webtop/drl/objectId/"+gnosisNodeId;
String s3="') where com_id="+me.getKey().toString().substring(1)+"";
Statement stmt1=null;
//http://dmfwebtop65.pfizer.com/webtop/drl/objectId/0901201b8239cefb
try {
String updateString1 = s1+s2+s3;
stmt1 = conn.createStatement();
int rows =stmt1.executeUpdate(updateString1);
if (rows>0) {
addLabel(sheet, 0, update, me.getKey().toString().substring(1));
addLabel(sheet, 1, update, me.getValue().toString().substring(1));
addLabel(sheet, 2, update,gnosisNodeId );
update++;
System.out.println("Update Success="+me.getKey().toString().substring(1)+ "-->" +me.getValue().toString().substring(1));
}
else
{
System.out.println("Not Updated="+me.getKey().toString().substring(1)+ "-->" +me.getValue().toString().substring(1));
}
} catch (SQLException e) {
System.out.println("No Connect" + e);
} catch (Exception e) {
System.out.println("Error "+e.getMessage());
}
}
else{System.out.println("No gnosis id found for ObjectID="+me.getKey().toString().substring(1)); }
}//While
} //try
catch (Exception e) {
e.printStackTrace();
}
}//Main try
catch (Exception e) {
e.printStackTrace();
}
} //method
private void addCaption(WritableSheet sheet, int column, int row, String s)
throws RowsExceededException, WriteException {
Label label;
label = new Label(column, row, s, timesBoldUnderline);
sheet.addCell(label);
}
private void addNumber(WritableSheet sheet, int column, int row,
Integer integer) throws WriteException, RowsExceededException {
Number number;
number = new Number(column, row, integer, times);
sheet.addCell(number);
}
private void addLabel(WritableSheet sheet, int column, int row, String s)
throws WriteException, RowsExceededException {
Label label;
label = new Label(column, row, s, times);
sheet.addCell(label);
}
public static void main(String[] args) throws WriteException, IOException {
DscMigration test = new DscMigration();
test.setOutputFile("C:/Documents and Settings/nithya/Desktop/DSC/Report/Mapping.xls");
test.write();
System.out
.println("Please check the result file under C:/Documents and Settings/nithya/Desktop/DSC/Report/Report.xls ");
}
}
XXXXInternal Use
Based on WTTE-0043 ELC Maintenance Release and Bug Fix Plan Template
Version 4.0 Effective Date: 01-Jul-2010
//Bug Fix Plan
Author:
1 Approval Signatures
Table of Contents
I have authored this deliverable to document the plan for executing a maintenance release or bug fix to project.
NAME DATE
I have authored this deliverable to document the plan for executing a maintenance release or bug fix to XXX Plus v4.5.
NAME DATE
I approve this change and agree that this record represents the accurate and complete plan for executing the maintenance release or bug fix, and fully supports the implementation, testing and release activities for this project.
NAME DATE
I have reviewed the content of this record and found that it meets the applicable BT compliance requirements.
NAME DATE
Signatures
2 Introduction
This project deliverable documents the requested change, planned approach, development solution, test plan, test results and release approval for a maintenance release or and bug fix to project.
3 Change Request
Requestor Name:
XX
Object/
System Name:
project
Priority (High/Medium/Low):
High
Change Request No.:
NA
Change Request Date:
22-NOV-2011
Description of Problem or Requested Change:
Estimated Development Time Needed:
1 day (approx.)
4)4 Maintenance Release and Bug Fix Approach
5 Development Solution
8 Supporting References
9 Revision History
I am using iText-Java to split PDFs at bookmark level.
Does anybody know or have any examples for splitting a PDF at bookmarks that exist at a level 2 or 3?
For ex: I have the bookmarks in the following levels:
Father
|-Son
|-Son
|-Daughter
|-|-Grand son
|-|-Grand daughter
Right now I have below code to read the bookmark which reads the base bookmark(Father). Basically SimpleBookmark.getBookmark(reader) line did all the work.
But I want to read the level 2 and level 3 bookmarks to split the content present between those inner level bookmarks.
public static void splitPDFByBookmarks(String pdf, String outputFolder){
try
{
PdfReader reader = new PdfReader(pdf);
//List of bookmarks: each bookmark is a map with values for title, page, etc
List<HashMap> bookmarks = SimpleBookmark.getBookmark(reader);
for(int i=0; i<bookmarks.size(); i++){
HashMap bm = bookmarks.get(i);
HashMap nextBM = i==bookmarks.size()-1 ? null : bookmarks.get(i+1);
//In my case I needed to split the title string
String title = ((String)bm.get("Title")).split(" ")[2];
log.debug("Titel: " + title);
String startPage = ((String)bm.get("Page")).split(" ")[0];
String startPageNextBM = nextBM==null ? "" + (reader.getNumberOfPages() + 1) : ((String)nextBM.get("Page")).split(" ")[0];
log.debug("Page: " + startPage);
log.debug("------------------");
extractBookmarkToPDF(reader, Integer.valueOf(startPage), Integer.valueOf(startPageNextBM), title + ".pdf",outputFolder);
}
}
catch (IOException e)
{
log.error(e.getMessage());
}
}
private static void extractBookmarkToPDF(PdfReader reader, int pageFrom, int pageTo, String outputName, String outputFolder){
Document document = new Document();
OutputStream os = null;
try{
os = new FileOutputStream(outputFolder + outputName);
// Create a writer for the outputstream
PdfWriter writer = PdfWriter.getInstance(document, os);
document.open();
PdfContentByte cb = writer.getDirectContent(); // Holds the PDF data
PdfImportedPage page;
while(pageFrom < pageTo) {
document.newPage();
page = writer.getImportedPage(reader, pageFrom);
cb.addTemplate(page, 0, 0);
pageFrom++;
}
os.flush();
document.close();
os.close();
}catch(Exception ex){
log.error(ex.getMessage());
}finally {
if (document.isOpen())
document.close();
try {
if (os != null)
os.close();
} catch (IOException ioe) {
log.error(ioe.getMessage());
}
}
}
Your help is much appreciated.
Thanks in advance! :)
You get an ArrayList<HashMap> when you call SimpleBookmark.getBookmark(reader); (do the cast if you need it). Try to iterate through that Arraylist and see its structure. If a bookmarks have sons (as you call it), it will contains another list with the same structure.
A recursive method could be the solution.
Reference for those who are looking at this using itext7
public void walkOutlines(PdfOutline outline, Map<String, PdfObject> names, PdfDocument pdfDocument,List<String>titles,List<Integer>pageNum) { //----------loop traversing all paths
for (PdfOutline child : outline.getAllChildren()){
if(child.getDestination() != null) {
prepareIndexFile(child,names,pdfDocument,titles,pageNum,list);
}
}
}
//-----Getting pageNumbers from outlines
public void prepareIndexFile(PdfOutline outline, Map<String, PdfObject> names, PdfDocument pdfDocument,List<String>titles,List<Integer>pageNum) {
String title = outline.getTitle();
PdfDestination pdfDestination = outline.getDestination();
String pdfStr = ((PdfString)pdfDestination.getPdfObject()).toUnicodeString();
PdfArray array = (PdfArray) names.get(pdfStr);
PdfObject pdfObj = array != null ? array.get(0) : null;
Integer pageNumber = pdfDocument.getPageNumber((PdfDictionary)pdfObj);
titles.add(title);
pageNum.add(pageNumber);
if(outline.getAllChildren().size() > 0) {
for (PdfOutline child : outline.getAllChildren()){
prepareIndexFile(child,names,pdfDocument,titles,pageNum);
}
}
}
public boolean splitPdf(String inputFile, final String outputFolder) {
boolean splitSuccess = true;
PdfDocument pdfDoc = null;
try {
PdfReader pdfReaderNew = new PdfReader(inputFile);
pdfDoc = new PdfDocument(pdfReaderNew);
final List<String> titles = new ArrayList<String>();
List<Integer> pageNum = new ArrayList<Integer>();
PdfNameTree destsTree = pdfDoc.getCatalog().getNameTree(PdfName.Dests);
Map<String, PdfObject> names = destsTree.getNames();//--------------------------------------Core logic for getting names
PdfOutline root = pdfDoc.getOutlines(false);//--------------------------------------Core logic for getting outlines
walkOutlines(root,names, pdfDoc, titles, pageNum,content); //------Logic to get bookmarks and pageNumbers
if (titles == null || titles.size()==0) {
splitSuccess = false;
}else { //------Proceed if it has bookmarks
for(int i=0;i<titles.size();i++) {
String title = titles.get(i);
String startPageNmStr =""+pageNum.get(i);
int startPage = Integer.parseInt(startPageNmStr);
int endPage = startPage;
if(i == titles.size() - 1) {
endPage = pdfDoc.getNumberOfPages();
}else {
int nextPage = pageNum.get(i+1);
if(nextPage > startPage) {
endPage = nextPage - 1;
}else {
endPage = nextPage;
}
}
String outFileName = outputFolder + File.separator + getFileName(title) + ".pdf";
PdfWriter pdfWriter = new PdfWriter(outFileName);
PdfDocument newDocument = new PdfDocument(pdfWriter, new DocumentProperties().setEventCountingMetaInfo(null));
pdfDoc.copyPagesTo(startPage, endPage, newDocument);
newDocument.close();
pdfWriter.close();
}
}
}catch(Exception e){
//---log
}
}
I am trying to write a pdf conversion, that will take a pdf containing 1-up portrait pages, and create a new document, but merge every 2 pages into one 2-up landscape page
ie.
the following code will scale down the content 50%, but I cant figure out how to make the new page landscape, while injecting the other page as portrait, and injecting into the top left, and right of centre
public static void main(String[] args) throws IOException, DocumentException, COSVisitorException {
scalePages("c:/pdf/in.pdf", "c:/pdf/out" + new Date().getTime() + ".pdf", 0.50f);
}
public static void scalePages(String inFile, String outFile, float scale ) throws IOException, COSVisitorException {
PDDocument doc1 = null;
try {
doc1 = PDDocument.load( inFile );
List allPages = doc1.getDocumentCatalog().getAllPages();
for( int i=0; i<allPages.size(); i++ ) {
PDPage page1 = (PDPage)allPages.get(i );
PDRectangle mediaBox = page1.getMediaBox();
float oldX = mediaBox.getUpperRightX();
float newX = oldX * scale;
float oldY = mediaBox.getUpperRightY();
float newY = oldY * scale;
mediaBox.setUpperRightX(newX);
mediaBox.setUpperRightY(newY);
PDFStreamParser parser = new PDFStreamParser(page1.getContents());
parser.parse();
List tokens = parser.getTokens();
tokens.add(0,new COSFloat(scale));
tokens.add(1,new COSInteger(0));
tokens.add(2,new COSInteger(0));
tokens.add(3,new COSFloat(scale));
tokens.add(4,new COSInteger(0));
tokens.add(5,new COSInteger(0));
tokens.add(6,PDFOperator.getOperator("cm"));
PDStream newContents = new PDStream( doc1 );
ContentStreamWriter writer = new ContentStreamWriter( newContents.createOutputStream() );
writer.writeTokens( tokens );
newContents.addCompression();
page1.setContents(newContents);
//page1.setRotation(90);
mediaBox.setUpperRightX(oldX);
mediaBox.setUpperRightY(oldY);
}
doc1.save( outFile );
} finally {
if( doc1 != null ) {
doc1.close();
}
}
}
so the result is as follows
any pointers would be greatly appreciated
Here is an example that "stitches" two one page PDFs side-by-side and saves result in a new file using PDFBox. Enjoy!
function void generateSideBySidePDF() {
File pdf1File = new File(FILE1_PATH);
File pdf2File = new File(FILE2_PATH);
File outPdfFile = new File(OUTFILE_PATH);
PDDocument pdf1 = null;
PDDocument pdf2 = null;
PDDocument outPdf = null;
try {
pdf1 = PDDocument.load(pdf1File);
pdf2 = PDDocument.load(pdf2File);
outPdf = new PDDocument();
// Create output PDF frame
PDRectangle pdf1Frame = pdf1.getPage(0).getCropBox();
PDRectangle pdf2Frame = pdf2.getPage(0).getCropBox();
PDRectangle outPdfFrame = new PDRectangle(pdf1Frame.getWidth()+pdf2Frame.getWidth(), Math.max(pdf1Frame.getHeight(), pdf2Frame.getHeight()));
// Create output page with calculated frame and add it to the document
COSDictionary dict = new COSDictionary();
dict.setItem(COSName.TYPE, COSName.PAGE);
dict.setItem(COSName.MEDIA_BOX, outPdfFrame);
dict.setItem(COSName.CROP_BOX, outPdfFrame);
dict.setItem(COSName.ART_BOX, outPdfFrame);
PDPage outPdfPage = new PDPage(dict);
outPdf.addPage(outPdfPage);
// Source PDF pages has to be imported as form XObjects to be able to insert them at a specific point in the output page
LayerUtility layerUtility = new LayerUtility(outPdf);
PDFormXObject formPdf1 = layerUtility.importPageAsForm(pdf1, 0);
PDFormXObject formPdf2 = layerUtility.importPageAsForm(pdf2, 0);
// Add form objects to output page
AffineTransform afLeft = new AffineTransform();
layerUtility.appendFormAsLayer(outPdfPage, formPdf1, afLeft, "left");
AffineTransform afRight = AffineTransform.getTranslateInstance(pdf1Frame.getWidth(), 0.0);
layerUtility.appendFormAsLayer(outPdfPage, formPdf2, afRight, "right");
outPdf.save(outPdfFile);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (pdf1 != null) pdf1.close();
if (pdf2 != null) pdf2.close();
if (outPdf != null) outPdf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I ended up doing this with itext
private String createTwoUp(String originalPdfFile) throws IOException, DocumentException {
String newFilename = FilenameUtils.getBaseName(originalPdfFile) + "_2up." + FilenameUtils.getExtension(originalPdfFile);
newFilename = FilenameUtils.concat(getPdfFileFolder(), newFilename);
PdfReader reader = new PdfReader(originalPdfFile);
Document doc = new Document(new RectangleReadOnly(842f, 595f), 0, 0, 0, 0);
PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(newFilename));
doc.open();
int totalPages = reader.getNumberOfPages();
for (int i = 1; i <= totalPages; i = i + 2) {
doc.newPage();
PdfContentByte cb = writer.getDirectContent();
PdfImportedPage page = writer.getImportedPage(reader, i); // page #1
float documentWidth = doc.getPageSize().getWidth() / 2;
float documentHeight = doc.getPageSize().getHeight();
if (i > 1) {
documentHeight = documentHeight - 65f;
}
float pageWidth = page.getWidth();
float pageHeight = page.getHeight();
float widthScale = documentWidth / pageWidth;
float heightScale = documentHeight / pageHeight;
float scale = Math.min(widthScale, heightScale);
//float offsetX = 50f;
float offsetX = (documentWidth - (pageWidth * scale)) / 2;
float offsetY = 0f;
cb.addTemplate(page, scale, 0, 0, scale, offsetX, offsetY);
if (i+1 <= totalPages) {
PdfImportedPage page2 = writer.getImportedPage(reader, i+1); // page #2
pageWidth = page.getWidth();
pageHeight = page.getHeight();
widthScale = documentWidth / pageWidth;
heightScale = documentHeight / pageHeight;
scale = Math.min(widthScale, heightScale);
offsetX = ((documentWidth - (pageWidth * scale)) / 2) + documentWidth;
cb.addTemplate(page2, scale, 0, 0, scale, offsetX, offsetY);
}
}
doc.close();
return newFilename;
}