I want to create 4 pdf files using iText. While running the code the first two of are successfully created. The remaning two throw an Exception "ExceptionConverter: java.io.IOException: The document has no pages."
Here is the code for pdf creation part:
public static Boolean createPDFFile(String filename, int headerType, List<DremelitemDetails> itemDetails) {
try {
path = new File(".").getCanonicalPath();
column = 0;
// create the pdf file
props.load(new FileInputStream("Properties\\eng.properties"));
COLUMNS = new float[][] {
{ MARGIN_LEFT, MARGIN_BOTTOM, (PageSize.LETTER.rotate().getWidth() - MARGIN_ENTER_COLUMNS) / 2,
PageSize.LETTER.rotate().getTop(MARGIN_TOP) },
{ (PageSize.LETTER.rotate().getWidth() + MARGIN_ENTER_COLUMNS) / 2, MARGIN_BOTTOM,
PageSize.LETTER.rotate().getRight(MARGIN_RIGHT), PageSize.LETTER.rotate().getTop(MARGIN_TOP) } };
String fontPath = "font\\arialuni.TTF";
unicodeFont = BaseFont.createFont(fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
mmPDFDocument = new Document(PageSize.LETTER.rotate(), MARGIN_LEFT, MARGIN_RIGHT, MARGIN_TOP, MARGIN_BOTTOM);
pdfWriter = PdfWriter.getInstance(mmPDFDocument, new FileOutputStream(filename));
mmPDFDocument.setPageSize(PageSize.LETTER.rotate());
/*String[] footer = { props.getProperty("header"), "fdftfdbfbug",
"\u00a9" + props.getProperty("footer1"), props.getProperty("footer2")};*/
String[] footer = { "SUMMARY OF PROJECTS", "Home Décor",
"\u00a92011 Robert Bosch Tool Corporation. All Rigths Reserved.",
"Web content and services - on demand, on your printer www.eprintcentre.com" };
pdfWriter.setPageEvent(new HeaderFooter(mmPDFDocument.right() - mmPDFDocument.left(), footer, path, headerType, unicodeFont));
mmPDFDocument.open();
COLUMNS[0][3] = mmPDFDocument.top();
COLUMNS[1][3] = mmPDFDocument.top();
pdfColumn = new ColumnText(pdfWriter.getDirectContent());
pdfColumn.setSimpleColumn(COLUMNS[column][0], COLUMNS[column][1], COLUMNS[column][2], COLUMNS[column][3]);
pdfColumn.setSpaceCharRatio(PdfWriter.NO_SPACE_CHAR_RATIO);
/* For generating Pdf */
addItemDetails(itemDetails);
mmPDFDocument.close();
} catch (FileNotFoundException e) {
System.out.println("FileNotFoundException-------"+e);
closePDFFile();
return false;
} catch (DocumentException e) {
System.out.println("DocumentException-------"+e);
closePDFFile();
return false;
} catch (Exception e) {
System.out.println("Exception-------"+e);
return false;
}
return true;
}
public static void main(String[] args) {
DremelData dremelData = new DremelData();
DremelPDFBulid dremelPDFBulid = new DremelPDFBulid();
Document doc = dremelData.readXml("C:\\eng.xml");
ArrayList<DremelitemDetails> homeDeco = dremelData.parseNode(1, 11, doc);
ArrayList<DremelitemDetails> artsAndCrafts = dremelData.parseNode(12, 24, doc);
ArrayList<DremelitemDetails> seasonalIdeas = dremelData.parseNode(25, 36, doc);
ArrayList<DremelitemDetails> DIYRestoration = dremelData.parseNode(37, 49, doc);
try {
dremelPDFBulid.createPDFFile("c:\\sam1.pdf", 0, homeDeco);
dremelPDFBulid.createPDFFile("c:\\sam2.pdf", 1, artsAndCrafts);
dremelPDFBulid.createPDFFile("c:\\sam3.pdf", 2, seasonalIdeas);
dremelPDFBulid.createPDFFile("c:\\sam4.pdf", 3, DIYRestoration);
} catch (Exception e) {
System.out.println("Error in readXml : " + e.toString());
}
}
In the above code the content of sam3 and samp4 pdf's are empty and showing "The document has no pages." exception
Related
I want to flatten a pdf with signatures from a form but I am using this code and when I generate the final pdf I can still delete the signature. What I want is that when I generate the final pdf, I cannot delete anything at all from the pdf
private static void flattenPDF(String src, String dst) throws IOException {
PDDocument doc = null;
try {
doc = PDDocument.load(new File(src));
} catch (IOException e) {
System.out.println("Exception: " + e.getMessage());
}
PDDocumentCatalog catalog = doc.getDocumentCatalog();
PDAcroForm acroForm = catalog.getAcroForm();
if(acroForm == null) acroForm = new PDAcroForm(PDDocument.load(new File(src)));
PDResources resources = new PDResources();
List<PDField> fields = new ArrayList<>(acroForm.getFields());
processFields(fields, resources);
acroForm.setDefaultResources(resources);
try {
acroForm.flatten();
doc.save(dst);
doc.close();
} catch (IOException e) {
System.out.println("Exception: " + e.getMessage());
}
}
private static void processFields(List<PDField> fields, PDResources resources) {
fields.stream().forEach(f -> {
f.setReadOnly(true);
COSDictionary cosObject = f.getCOSObject();
String value = cosObject.getString(COSName.DV) == null ?
cosObject.getString(COSName.V) : cosObject.getString(COSName.DV);
System.out.println("Setting " + f.getFullyQualifiedName() + ": " + value);
try {
f.setValue(value);
} catch (IOException e) {
if (e.getMessage().matches("Could not find font: /.*")) {
String fontName = e.getMessage().replaceAll("^[^/]*/", "");
System.out.println("Adding fallback font for: " + fontName);
resources.put(COSName.getPDFName(fontName), PDType1Font.HELVETICA);
try {
f.setValue(value);
} catch (IOException e1) {
e1.printStackTrace();
}
} else {
e.printStackTrace();
}
}
if (f instanceof PDNonTerminalField) {
processFields(((PDNonTerminalField) f).getChildren(), resources);
}
});
}
I have simple piece of code that writes a PDF sometime this PDF will contain RTL languages like Hebrew or Arabic.
I was able to manipulate the text and mirror it using Bidi (Ibm lib)
But the text is still running in reverse
In English it would be something like:
instead of:
The quick
brown fox
jumps over
the lazy dog
It appears as:
the lazy dog
jumps over
brown fox
The quick
Complete code:
#Test
public void generatePdf() {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-hh.mm.ss");
String dest = "c:\\temp\\" + formatter.format(Calendar.getInstance().getTime()) + ".pdf";
String fontPath = "C:\\Windows\\Fonts\\ARIALUNI.TTF";
FontProgramFactory.registerFont(fontPath, "arialUnicode");
OutputStream pdfFile = null;
Document doc = null;
try {
ByteArrayOutputStream output = new ByteArrayOutputStream();
PdfFont PdfFont = PdfFontFactory.createRegisteredFont("arialUnicode", PdfEncodings.IDENTITY_H, true);
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(output));
pdfDoc.setDefaultPageSize(PageSize.A4);
pdfDoc.addFont(PdfFont);
doc = new Document(pdfDoc);
doc.setBaseDirection(BaseDirection.RIGHT_TO_LEFT);
String txt = "בתשרי נתן הדקל פרי שחום נחמד בחשוון ירד יורה ועל גגי רקד בכסלו נרקיס הופיע בטבת ברד ובשבט חמה הפציעה ליום אחד. 1234 באדר עלה ניחוח מן הפרדסים בניסן הונפו בכוח כל החרמשים";
Bidi bidi = new Bidi();
bidi.setPara(txt, Bidi.RTL, null);
String mirrTxt = bidi.writeReordered(Bidi.DO_MIRRORING);
Paragraph paragraph1 = new Paragraph(mirrTxt)
.setFont(PdfFont)
.setFontSize(9)
.setTextAlignment(TextAlignment.CENTER)
.setHeight(200)
.setWidth(70);
paragraph1.setBorder(new SolidBorder(3));
doc.add(paragraph1);
Paragraph paragraph2 = new Paragraph(txt)
.setFont(PdfFont)
.setFontSize(9)
.setTextAlignment(TextAlignment.CENTER)
.setHeight(200)
.setWidth(70);
paragraph2.setBorder(new SolidBorder(3));
doc.add(paragraph2);
doc.close();
doc.flush();
pdfFile = new FileOutputStream(dest);
pdfFile.write(output.toByteArray());
ProcessBuilder b = new ProcessBuilder("cmd.exe","/C","explorer " + dest);
b.start();
} catch (Exception e) {
e.printStackTrace();
}finally {
try {pdfFile.close();} catch (IOException e) {e.printStackTrace();}
}
}
The only solution that I have found with iText7 and IBM ICU4J without any other third party libraries is to first render the lines and then mirror them one by one. This requires a helper class LineMirroring and it's not precisely the most elegant solution, but will produce the output that you expect.
Lines mirroring class:
public class LineMirroring {
private final PageSize pageSize;
private final String fontName;
private final int fontSize;
public LineMirroring(PageSize pageSize, String fontName, int fontSize) {
this.pageSize = pageSize;
this.fontName = fontName;
this.fontSize = fontSize;
}
public String mirrorParagraph(String input, int height, int width, Border border) {
final StringBuilder mirrored = new StringBuilder();
try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
PdfFont font = PdfFontFactory.createRegisteredFont(fontName, PdfEncodings.IDENTITY_H, true);
final PdfWriter writer = new PdfWriter(output);
final PdfDocument pdfDoc = new PdfDocument(writer);
pdfDoc.setDefaultPageSize(pageSize);
pdfDoc.addFont(font);
final Document doc = new Document(pdfDoc);
doc.setBaseDirection(BaseDirection.RIGHT_TO_LEFT);
final LineTrackingParagraph paragraph = new LineTrackingParagraph(input);
paragraph.setFont(font)
.setFontSize(fontSize)
.setTextAlignment(TextAlignment.RIGHT)
.setHeight(height)
.setWidth(width)
.setBorder(border);
LineTrackingParagraphRenderer renderer = new LineTrackingParagraphRenderer(paragraph);
doc.add(paragraph);
Bidi bidi;
for (LineRenderer lr : paragraph.getWrittenLines()) {
bidi = new Bidi(((TextRenderer) lr.getChildRenderers().get(0)).getText().toString(), Bidi.RTL);
mirrored.append(bidi.writeReordered(Bidi.DO_MIRRORING));
}
doc.close();
pdfDoc.close();
writer.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
return mirrored.toString();
}
private class LineTrackingParagraph extends Paragraph {
private List<LineRenderer> lines;
public LineTrackingParagraph(String text) {
super(text);
}
public void addWrittenLines(List<LineRenderer> lines) {
this.lines = lines;
}
public List<LineRenderer> getWrittenLines() {
return lines;
}
#Override
protected IRenderer makeNewRenderer() {
return new LineTrackingParagraphRenderer(this);
}
}
private class LineTrackingParagraphRenderer extends ParagraphRenderer {
public LineTrackingParagraphRenderer(LineTrackingParagraph modelElement) {
super(modelElement);
}
#Override
public void drawChildren(DrawContext drawContext) {
((LineTrackingParagraph)modelElement).addWrittenLines(lines);
super.drawChildren(drawContext);
}
#Override
public IRenderer getNextRenderer() {
return new LineTrackingParagraphRenderer((LineTrackingParagraph) modelElement);
}
}
}
Minimal JUnit Test:
public class Itext7HebrewTest {
#Test
public void generatePdf() {
final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-hh.mm.ss");
final String dest = "F:\\Temp\\" + formatter.format(Calendar.getInstance().getTime()) + ".pdf";
final String fontPath = "C:\\Windows\\Fonts\\ARIALUNI.TTF";
final String fontName = "arialUnicode";
FontProgramFactory.registerFont(fontPath, "arialUnicode");
try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
PdfFont arial = PdfFontFactory.createRegisteredFont(fontName, PdfEncodings.IDENTITY_H, true);
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(output));
pdfDoc.setDefaultPageSize(PageSize.A4);
pdfDoc.addFont(arial);
LineMirroring mirroring = new LineMirroring(pdfDoc.getDefaultPageSize(), fontName,9);
Document doc = new Document(pdfDoc);
doc.setBaseDirection(BaseDirection.RIGHT_TO_LEFT);
final String txt = "בתשרי נתן הדקל פרי שחום נחמד בחשוון ירד יורה ועל גגי רקד בכסלו נרקיס הופיע בטבת ברד ובשבט חמה הפציעה ליום אחד. 1234 באדר עלה ניחוח מן הפרדסים בניסן הונפו בכוח כל החרמשים";
final int height = 200;
final int width = 70;
final Border border = new SolidBorder(3);
Paragraph paragraph1 = new Paragraph(mirroring.mirrorParagraph(txt, height, width, border));
paragraph1.setFont(arial)
.setFontSize(9)
.setTextAlignment(TextAlignment.RIGHT)
.setHeight(height)
.setWidth(width)
.setBorder(border);
doc.add(paragraph1);
doc.close();
doc.flush();
try (FileOutputStream pdfFile = new FileOutputStream(dest)) {
pdfFile.write(output.toByteArray());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
I'm working on a JAVA web application, I need to merge multiple docx files into one docx file using JAVA.
the method takes a list of File as parameter, the output is a single docx file that contains all data concatenated from Files in input.
I tried this code but it did not work for me:
public File mergeInOneFile(List<File> files) throws IOException, InvalidFormatException, XmlException {
List<CTBody> sourceBody = new ArrayList<>();
for (File file : files) {
OPCPackage srcFile = OPCPackage.open(file);
XWPFDocument srcDocument = new XWPFDocument(srcFile);
CTBody srcBody = srcDocument.getDocument().getBody();
sourceBody.add(srcBody);
}
CTBody source = sourceBody.get(0);
sourceBody.remove(0);
while (sourceBody.size() != 0){
appendBody(source, sourceBody.get(0));
sourceBody.remove(0);
}
return (File) source;
}
private static void appendBody(CTBody src, CTBody append) throws XmlException {
XmlOptions optionsOuter = new XmlOptions();
optionsOuter.setSaveOuter();
String appendString = append.xmlText(optionsOuter);
String srcString = src.xmlText();
String prefix = srcString.substring(0,srcString.indexOf(">")+1);
String mainPart = srcString.substring(srcString.indexOf(">")+1,srcString.lastIndexOf("<"));
String suffix = srcString.substring( srcString.lastIndexOf("<") );
String addPart = appendString.substring(appendString.indexOf(">") + 1, appendString.lastIndexOf("<"));
CTBody makeBody = CTBody.Factory.parse(prefix+mainPart+addPart+suffix);
src.set(makeBody);
}
}
This method did not acheive my purpose. Any other suggestions ?
The error is clearly because of this line: return (File) source.
source is a CTBody type and you cast it to File while they are not related.
I have solved the issue of merging a list of docx files in one file, this is my code :
public File merge(final List<File> files) throws IoAppException, OtherAppException {
Path outPath = this.fileStorageService.getPath()
.resolve(UUID.randomUUID().toString() + Directory.DOCX_EXTENSION);
File outFile = outPath.toFile();
try (OutputStream os = new FileOutputStream(outFile);
InputStream is = new FileInputStream(files.get(0));
XWPFDocument doc = new XWPFDocument(is);) {
CTBody ctBody = doc.getDocument().getBody();
for (int i = 1; i < files.size(); i++) {
try (InputStream isI = new FileInputStream(files.get(i)); XWPFDocument docI = new XWPFDocument(isI);) {
CTBody ctBodyI = docI.getDocument().getBody();
appendBody(ctBody, ctBodyI);
} catch (Exception e) {
e.printStackTrace();
throw new OtherAppException("", e);
}
}
doc.write(os);
return outFile;
} catch (FileNotFoundException e) {
e.printStackTrace();
throw new IoAppException("", e);
} catch (IOException e) {
e.printStackTrace();
throw new IoAppException("", e);
}
}
private static void appendBody(CTBody src, CTBody append) throws XmlException {
XmlOptions optionsOuter = new XmlOptions();
optionsOuter.setSaveOuter();
String appendString = append.xmlText(optionsOuter);
String srcString = src.xmlText();
String prefix = srcString.substring(0, srcString.indexOf(">") + 1);
String mainPart = srcString.substring(srcString.indexOf(">") + 1, srcString.lastIndexOf("<"));
String suffix = srcString.substring(srcString.lastIndexOf("<"));
String addPart = appendString.substring(appendString.indexOf(">") + 1, appendString.lastIndexOf("<"));
CTBody makeBody;
try {
makeBody = CTBody.Factory.parse(prefix + mainPart + addPart + suffix);
} catch (XmlException e) {
e.printStackTrace();
throw new XmlException("", e);
}
src.set(makeBody);
}
I need to create a pdf file from plain text files. I supposed that the simplest method would be read these files and print them to a PDF printer.
My problem is that if I print to a pdf printer, the result will be an empty pdf file. If I print to Microsoft XPS Document Writer, the file is created in plain text format, not in oxps format.
I would be satisfied with a two or three step solution. (Eg. converting to xps first then to pdf using ghostscript, or something similar).
I have tried a couple of pdf printers such as: CutePDF, Microsoft PDF writer, Bullzip PDF. The result is the same for each one.
The environment is Java 1.7/1.8 Win10
private void print() {
try {
DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
PrintRequestAttributeSet patts = new HashPrintRequestAttributeSet();
PrintService[] ps = PrintServiceLookup.lookupPrintServices(flavor, patts);
if (ps.length == 0) {
throw new IllegalStateException("No Printer found");
}
System.out.println("Available printers: " + Arrays.asList(ps));
PrintService myService = null;
for (PrintService printService : ps) {
if (printService.getName().equals("Microsoft XPS Document Writer")) { //
myService = printService;
break;
}
}
if (myService == null) {
throw new IllegalStateException("Printer not found");
}
myService.getSupportedDocFlavors();
DocPrintJob job = myService.createPrintJob();
FileInputStream fis1 = new FileInputStream("o:\\k\\t1.txt");
Doc pdfDoc = new SimpleDoc(fis1, DocFlavor.INPUT_STREAM.AUTOSENSE, null);
HashPrintRequestAttributeSet pr = new HashPrintRequestAttributeSet();
pr.add(OrientationRequested.PORTRAIT);
pr.add(new Copies(1));
pr.add(MediaSizeName.ISO_A4);
PrintJobWatcher pjw = new PrintJobWatcher(job);
job.print(pdfDoc, pr);
pjw.waitForDone();
fis1.close();
} catch (PrintException ex) {
Logger.getLogger(Docparser.class.getName()).log(Level.SEVERE, null, ex);
} catch (Exception ex) {
Logger.getLogger(Docparser.class.getName()).log(Level.SEVERE, null, ex);
}
}
class PrintJobWatcher {
boolean done = false;
PrintJobWatcher(DocPrintJob job) {
job.addPrintJobListener(new PrintJobAdapter() {
public void printJobCanceled(PrintJobEvent pje) {
allDone();
}
public void printJobCompleted(PrintJobEvent pje) {
allDone();
}
public void printJobFailed(PrintJobEvent pje) {
allDone();
}
public void printJobNoMoreEvents(PrintJobEvent pje) {
allDone();
}
void allDone() {
synchronized (PrintJobWatcher.this) {
done = true;
System.out.println("Printing done ...");
PrintJobWatcher.this.notify();
}
}
});
}
public synchronized void waitForDone() {
try {
while (!done) {
wait();
}
} catch (InterruptedException e) {
}
}
}
If you can install LibreOffice, it is possible to use the Java UNO API to do this.
There is a similar example here which will load and save a file: Java Convert Word to PDF with UNO. This could be used to convert your text file to PDF.
Alternatively, you could take the text file and send it directly to the printer using the same API.
The following JARs give access to the UNO API. Ensure these are in your class path:
[Libre Office Dir]/URE/java/juh.jar
[Libre Office Dir]/URE/java/jurt.jar
[Libre Office Dir]/URE/java/ridl.jar
[Libre Office Dir]/program/classes/unoil.jar
[Libre Office Dir]/program
The following code will then take your sourceFile and print to the printer named "Local Printer 1".
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import com.sun.star.beans.PropertyValue;
import com.sun.star.frame.XComponentLoader;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.view.XPrintable;
public class DirectPrintTest
{
public static void main(String args[])
{
// set to the correct name of your printers
String printer = "Local Printer 1";// "Microsoft Print to PDF";
File sourceFile = new File("c:/projects/WelcomeTemplate.doc");
if (!sourceFile.canRead()) {
throw new RuntimeException("Can't read:" + sourceFile.getPath());
}
com.sun.star.uno.XComponentContext xContext = null;
try {
// get the remote office component context
xContext = com.sun.star.comp.helper.Bootstrap.bootstrap();
System.out.println("Connected to a running office ...");
// get the remote office service manager
com.sun.star.lang.XMultiComponentFactory xMCF = xContext
.getServiceManager();
Object oDesktop = xMCF.createInstanceWithContext(
"com.sun.star.frame.Desktop", xContext);
com.sun.star.frame.XComponentLoader xCompLoader = (XComponentLoader) UnoRuntime
.queryInterface(com.sun.star.frame.XComponentLoader.class,
oDesktop);
StringBuffer sUrl = new StringBuffer("file:///");
sUrl.append(sourceFile.getCanonicalPath().replace('\\', '/'));
List<PropertyValue> loadPropsList = new ArrayList<PropertyValue>();
PropertyValue pv = new PropertyValue();
pv.Name = "Hidden";
pv.Value = Boolean.TRUE;
loadPropsList.add(pv);
PropertyValue[] loadProps = new PropertyValue[loadPropsList.size()];
loadPropsList.toArray(loadProps);
// Load a Writer document, which will be automatically displayed
com.sun.star.lang.XComponent xComp = xCompLoader
.loadComponentFromURL(sUrl.toString(), "_blank", 0,
loadProps);
// Querying for the interface XPrintable on the loaded document
com.sun.star.view.XPrintable xPrintable = (XPrintable) UnoRuntime
.queryInterface(com.sun.star.view.XPrintable.class, xComp);
// Setting the property "Name" for the favoured printer (name of
// IP address)
com.sun.star.beans.PropertyValue propertyValue[] = new com.sun.star.beans.PropertyValue[2];
propertyValue[0] = new com.sun.star.beans.PropertyValue();
propertyValue[0].Name = "Name";
propertyValue[0].Value = printer;
// Setting the name of the printer
xPrintable.setPrinter(propertyValue);
propertyValue[0] = new com.sun.star.beans.PropertyValue();
propertyValue[0].Name = "Wait";
propertyValue[0].Value = Boolean.TRUE;
// Printing the loaded document
System.out.println("sending print");
xPrintable.print(propertyValue);
System.out.println("closing doc");
((com.sun.star.util.XCloseable) UnoRuntime.queryInterface(
com.sun.star.util.XCloseable.class, xPrintable))
.close(true);
System.out.println("closed");
System.exit(0);
} catch (Exception e) {
e.printStackTrace(System.err);
System.exit(1);
}
}
}
Thank you for all. After two days struggling with various type of printers (I gave a chance to CUPS PDF printer too but I could not make it to print in landscape mode) I ended up using the Apache PDFbox.
It's only a POC solution but works and fits to my needs. I hope it will be useful for somebody.
( cleanTextContent() method removes some ESC control characters from the line to be printed. )
public void txt2pdf() {
float POINTS_PER_INCH = 72;
float POINTS_PER_MM = 1 / (10 * 2.54f) * POINTS_PER_INCH;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd HH:m.ss");
PDDocument doc = null;
try {
doc = new PDDocument();
PDPage page = new PDPage(new PDRectangle(297 * POINTS_PER_MM, 210 * POINTS_PER_MM));
doc.addPage(page);
PDPageContentStream content = new PDPageContentStream(doc, page);
//PDFont pdfFont = PDType1Font.HELVETICA;
PDFont pdfFont = PDTrueTypeFont.loadTTF(doc, new File("c:\\Windows\\Fonts\\lucon.ttf"));
float fontSize = 10;
float leading = 1.1f * fontSize;
PDRectangle mediabox = page.getMediaBox();
float margin = 20;
float startX = mediabox.getLowerLeftX() + margin;
float startY = mediabox.getUpperRightY() - margin;
content.setFont(pdfFont, fontSize);
content.beginText();
content.setLeading(leading);
content.newLineAtOffset(startX, startY);
BufferedReader fis1 = new BufferedReader(new InputStreamReader(new FileInputStream("o:\\k\\t1.txt"), "cp852"));
String inString;
//content.setRenderingMode(RenderingMode.FILL_STROKE);
float currentY = startY + 60;
float hitOsszesenOffset = 0;
int pageNumber = 1;
while ((inString = fis1.readLine()) != null) {
currentY -= leading;
if (currentY <= margin) {
content.newLineAtOffset(0, (mediabox.getLowerLeftX()-35));
content.showText("Date Generated: " + dateFormat.format(new Date()));
content.newLineAtOffset((mediabox.getUpperRightX() / 2), (mediabox.getLowerLeftX()));
content.showText(String.valueOf(pageNumber++)+" lap");
content.endText();
float yCordinate = currentY+30;
float sX = mediabox.getLowerLeftY()+ 35;
float endX = mediabox.getUpperRightX() - 35;
content.moveTo(sX, yCordinate);
content.lineTo(endX, yCordinate);
content.stroke();
content.close();
PDPage new_Page = new PDPage(new PDRectangle(297 * POINTS_PER_MM, 210 * POINTS_PER_MM));
doc.addPage(new_Page);
content = new PDPageContentStream(doc, new_Page);
content.beginText();
content.setFont(pdfFont, fontSize);
content.newLineAtOffset(startX, startY);
currentY = startY;
}
String ss = new String(inString.getBytes(), "UTF8");
ss = cleanTextContent(ss);
if (!ss.isEmpty()) {
if (ss.contains("JAN") || ss.contains("SUMMARY")) {
content.setRenderingMode(RenderingMode.FILL_STROKE);
}
content.newLineAtOffset(0, -leading);
content.showText(ss);
}
content.setRenderingMode(RenderingMode.FILL);
}
content.newLineAtOffset((mediabox.getUpperRightX() / 2), (mediabox.getLowerLeftY()));
content.showText(String.valueOf(pageNumber++));
content.endText();
fis1.close();
content.close();
doc.save("o:\\k\\t1.pdf");
} catch (IOException ex) {
Logger.getLogger(Document_Creation.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if (doc != null) {
try {
doc.close();
} catch (IOException ex) {
Logger.getLogger(Document_Creation.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
While creating portfolio pdf, if any pdf size is large or it is having large no if pages in it, then portfolio pdf is not getting created. It does not throw any error as well. Please find the code below:
public byte[] createPortFolio(String directoryName) throws DocumentException, IOException {
Document document = new Document();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfWriter writer = PdfWriter.getInstance(document, baos);
document.open();
document.add(new Paragraph("This document contains a collection of PDFs, one per Stanley Kubrick movie."));
PdfIndirectReference parentFolderObjectReference = writer.getPdfIndirectReference();
PdfDictionary parentFolderObject = GetFolderDictionary(folderCount);
parentFolderObject.put(PdfName.NAME, new PdfString("Root"));
PdfCollection collection = new PdfCollection(PdfCollection.CUSTOM);
PdfCollectionSchema schema = getCollectionSchema();
collection.setSchema(schema);
PdfCollectionSort sort = new PdfCollectionSort("File");
sort.setSortOrder(true);
collection.setSort(sort);
collection.put(new PdfName("Folders"), parentFolderObjectReference);
writer.setCollection(collection);
listFilesAndFilesSubDirectories(writer, collection, schema, directoryName, parentFolderObject, parentFolderObjectReference);
document.close();
return baos.toByteArray();
}
public void listFilesAndFilesSubDirectories(PdfWriter writer, PdfCollection collection, PdfCollectionSchema schema, String directoryName, PdfDictionary parentFolderObject, PdfIndirectReference parentIndirectReference) throws DocumentException, IOException {
File directory = new File(directoryName);
//get all the files from a directory
File[] fList = directory.listFiles();
String sStatus = "";
PdfIndirectReference siblingFolderObjectReference = null;
PdfDictionary siblingFolderObject = null;
PdfIndirectReference childFolderObjectReference = null;
PdfDictionary childFolderObject = null;
for (File file : fList) {
if (file.isFile()) {
createPdf(writer, schema, file, parentFolderObject);//adding PDF in Portfolio
} else if (file.isDirectory()) {
childFolderObjectReference = writer.getPdfIndirectReference();
folderCount++;
if (siblingFolderObject != null && parentIndirectReference.equals(siblingFolderObject.get(PdfName.PARENT))) {
siblingFolderObject.put(PdfName.NEXT, childFolderObjectReference);
writer.addToBody(siblingFolderObject, siblingFolderObjectReference);
} else {
parentFolderObject.put(new PdfName("Child"), childFolderObjectReference);
}
childFolderObject = GetFolderDictionary(folderCount);
childFolderObject.put(PdfName.NAME, new PdfString(file.getName()));
childFolderObject.put(PdfName.PARENT, parentIndirectReference);
siblingFolderObjectReference = childFolderObjectReference;
siblingFolderObject = childFolderObject;
writer.addToBody(parentFolderObject, parentIndirectReference);
writer.addToBody(childFolderObject, childFolderObjectReference);
listFilesAndFilesSubDirectories(writer, collection, schema, file.getAbsolutePath(), childFolderObject, childFolderObjectReference);
}
}
}
private void createPdf(PdfWriter writer, PdfCollectionSchema schema, File fileObj, PdfDictionary parentFolderObject) {
PdfFileSpecification fs=null;
PdfCollectionItem item;
//Adding first File
try{
fs = PdfFileSpecification.fileEmbedded(writer, fileObj.getPath(), fileObj.getName(), null, true, null, null);
//fs=fileEmbedded(writer, fileObj.getPath(), fileObj.getName(), null, true, null, null);
}
catch(Exception ex)
{
System.out.println("in Exception "+ex.getMessage());
ex.printStackTrace();
}
finally
{
System.out.println("in finally block");
}
item = new PdfCollectionItem(schema);
item.addItem("Type", "pdf");
fs.addCollectionItem(item);
try{
writer.addFileAttachment(fs);
}
catch(Exception ex)
{
System.out.println("in Exception2 "+ex.getMessage());
ex.printStackTrace();
}
finally{
System.out.println("in finally 2");
}
}
In createPdf() function, after first try block code neither runs nor throws any exception.