Apache PdfBox Rotate Crop Box Only Not Text - java

I am trying to go from text to pdf but have only one of the pages rotated 90 degress. Main reason is that some of my text documents are a bit too large and need to be in landscape to look normal. I have tried a few things but it seems like everything rotates the text too. Is there an easy way to rotate the pdf to landscape but keep the text the same rotation?
OutputStream outputStream = response.getOutputStream();
PDFMergerUtility pdfMergerUtility = new PDFMergerUtility();
Map<String, Documents> documents = getDocuments(user, documentReports);
try (PDDocument documentToPrint = new PDDocument()){
for(Document doc : documentReports){
TextToPDF textToPDF = new TextToPDF();
textToPDF.setFont(PDType1Font.COURIER);
textToPDF.setFontSize(8);
Document documentReport = documents.get(doc.getId());
try(PDDocument pdDocument = textToPDF.createPDFFromText(new InputStreamReader(new ByteArrayInputStream(documentReport.getReportText().getBytes())))) {
pdfMergerUtility.appendDocument(documentToPrint, pdDocument);
}
}
pdfMergerUtility.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
LocalDateTime localUtcTime = Java8TimeUtil.getCurrentUtcTime();
documentToPrint.getDocumentInformation().setTitle(localUtcTime.toString());
response.setHeader("Content-Disposition", "inline; filename=" + localUtcTime + ".pdf");
response.setContentType("application/pdf");
documentToPrint.save(outputStream);
}

So this might not work for everyone but I figured it out for my specific requirement. TextToPDF has a method called setLandscape before creating the pdf from text. textToPDF.setLandscape(true);

Related

Barcode in PDF not displaying in FireFox [duplicate]

I am running into strange issue with generated pdf's from iText7. The generated pdf's are opening properly in Adobe reader and Chrome browser. But the same pdf is opening partially in the Firefox browser. I am getting the below message in Firefox. The strange thing is other pdf, which are not generated via iText are properly rendering in firefox.
Java code
public static byte[] createPdf(List<String> htmlPages, PageSize pageSize, boolean rotate) throws IOException {
ConverterProperties properties = new ConverterProperties();
// Register classpath protocol handler to be able to load HTML resources from class patch
org.apache.catalina.webresources.TomcatURLStreamHandlerFactory.register();
properties.setBaseUri("classpath:/");
// properties.setBaseUri(baseUri);
FontProvider fontProvider = new DefaultFontProvider(true,false,false);
properties.setFontProvider(fontProvider);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
PdfDocument pdf = new PdfDocument(new PdfWriter(byteArrayOutputStream));
PdfMerger merger = new PdfMerger(pdf);
for (String htmlPage : htmlPages) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfDocument temp = new PdfDocument(new PdfWriter(baos));
if(rotate) {
temp.setDefaultPageSize(pageSize.rotate()); /** Page Size and Orientation */
} else {
temp.setDefaultPageSize(pageSize); /** Page Size and Orientation */
}
HtmlConverter.convertToPdf(htmlPage, temp, properties);
temp = new PdfDocument(new PdfReader(new ByteArrayInputStream(baos.toByteArray())));
merger.merge(temp, 1, temp.getNumberOfPages());
temp.close();
}
pdf.close();
byteArrayOutputStream.flush(); // Tried this
byteArrayOutputStream.close(); // Tried this
byte[] byteArray = byteArrayOutputStream.toByteArray();
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
try (FileOutputStream fileOuputStream = new FileOutputStream("D:\\Labels\\Label_"+timestamp.getTime()+".pdf")){
fileOuputStream.write(byteArray);
}
return byteArray;
}
Thanks in advance.
Edit 1:
You can find pdf and html/css for reproducing issue here.
When you embedded the images into your html using base64 URIs, something weird happened to the image of the barcode: Instead of the 205×59 bitmap image in labelData/barcode.png you embedded a 39578×44 image! (Yes, an image nearly a thousand times wider than high...)
The iText HtmlConverter embedded that image just fine but apparently Firefox has issues displaying an image with those dimensions even though (or probably because?) it is transformed into the desired dimensions (about four times wider than high) on the label. At least my Firefox installation stops drawing label contents right here. (Beware, the order of drawing in the PDF content is not identical to the of the HTML elements; in particular in the PDF the number 3232000... is drawn right before the barcode, not afterwards!)
On Firefox:
On Acrobat Reader:
Thus, you may want to check the transformation of the bar code image to the base64 image URI in your HTML file.

PDFBox TextToPdf keep font

I am currently converting a text document to pdf and rendering it to the browser and cannot seem to keep the font. The font is courier but gets converted to something else when it is converted to a pdf. Is there a easy way to just make it keep the default font? Or at least be able to set it after converting? here is the code.
public void downloadFile(HttpServletResponse response, List<Report> reports) throws IOException{
OutputStream outputStream = response.getOutputStream();
PDFMergerUtility pdfMergerUtility = new PDFMergerUtility();
PDDocument documentToPrint = new PDDocument();
for(Report report : reports){
PDDocument pdDocument = new TextToPDF().createPDFFromText(new InputStreamReader(
new FileInputStream(fileDirectory + File.separator + report.getFileLocation()), "UTF8")
);
pdfMergerUtility.appendDocument(documentToPrint, pdDocument);
}
pdfMergerUtility.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
response.setContentType("application/pdf");
response.addHeader("Content-Disposition", "inline; filename=" + "download.pdf");
documentToPrint.save(outputStream);
documentToPrint.close();
}
I have also tried setting it like the following before appending the document.
PDDocumentCatalog documentCatalog = pdDocument.getDocumentCatalog();
PDResources pdResources = documentCatalog.getPages().get(i).getResources();
pdResources.add(PDType1Font.COURIER);
documentCatalog.getPages().get(i++).setResources(pdResources);
But that does not seem to work either
Because I have a the font in the text document as courier.
No you don't, editors usually display it with Courier. So you have to set it because the default is Helvetica.
Change this:
PDDocument pdDocument = new TextToPDF().createPDFFromText(new InputStreamReader(....
to this:
TextToPDF textToPDF = new TextToPDF();
textToPDF.setFont(PDType1Font.COURIER);
textToPDF.createPDFFromText(new InputStreamReader(....

droidtext adding image doesn't work

I am desperately trying to insert an image into an existing pdf with droidtext.
The original version of this project was made with iText.
So the code already exists and was modified to fit for Android.
What I do is I take an existing PDF as background.
Insert text and crosses at specified positions within this pdf.
Like filling out a form.
This works quite well so far without changing the code drastically.
Now I want to set an image to the bottom of the page to sign the form.
I used my original code and adapted it a little.
Which doesn't work at all.
I tried to set the image at a specific position. Maybe that was the error.
So i tried to do it the "official" way.
The Pengiuns.jpg image is located on the sd-card.
try {
Document document = new Document();
File f=new File(Environment.getExternalStorageDirectory(), "SimpleImages.pdf");
PdfWriter.getInstance(document,new FileOutputStream(f));
document.open();
document.add(new Paragraph("Simple Image"));
String path = Environment.getExternalStorageDirectory()+"/Penguins.jpg";
if (new File(path).exists()) {
System.out.println("filesize: " + path + " = " + new File(path).length());
}
Image image =Image.getInstance(path);
document.add(image);
document.close();
} catch (Exception ex) {
System.out.println("narf");
}
But still no image at all.
What I get is an PDF with the words "Simple Image" on it and nothing else.
I can access the picture. I get the correct filesize by the if().
No exceptions are thrown.
So my questions are, how do I get an Image located on the SD-Card into my pdf?
What is the mistake here?
But most importantly how do I set the image to a specific location with size within the pdf?
In my original code i use setAbsolutePosition( x, y ) for that.
Eclipse is not complaining when I use it in the code but is it really working?
The reason why you are getting the "Simple Image" is because you have it in Paragraph. In order to add an image, use:
Image myImg1 = Image.getInstance(stream1.toByteArray());
If you want to have it as a footer in the last page you can use the following code but it works with text. You can try to manipulate it for image:
Phrase footerText = new Phrase("THIS REPORT HAS BEEN GENERATED USING INSPECTIONREPORT APP");
HeaderFooter pdfFooter = new HeaderFooter(footerText, false);
doc.setFooter(pdfFooter);
Here is sample code. Here I have uploaded an image to Imageview and then added to pdf. Hope this helps.
private String NameOfFolder = "/InspectionReport";
Document doc = new Document();
try { //Path to look for App folder
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + NameOfFolder;
String CurrentDateAndTime= getCurrentDateAndTime();
// If App folder is not there then create one
File dir = new File(path);
if(!dir.exists())
dir.mkdirs();
//Creating new file and naming it
int i = 1;
File file = new File(dir, "Inspection"+Integer.toString(i)+"-" + CurrentDateAndTime+".pdf");
while(file.exists()) {
file = new File(dir, "Inspection"+Integer.toString(i++)+"-" + CurrentDateAndTime+".pdf");}
String filep= file.toString();
FileOutputStream fOut = new FileOutputStream(file);
Log.d("PDFCreator", "PDF Path: " + path);
PdfWriter.getInstance(doc, fOut);
Toast.makeText(getApplicationContext(),filep , Toast.LENGTH_LONG).show();
//open the document
doc.open();
ImageView img1 = (ImageView)findViewById(R.id.img1);
ByteArrayOutputStream stream1 = new ByteArrayOutputStream();
Bitmap bitmap1 = ((BitmapDrawable)img1.getDrawable()).getBitmap();
bitmap1.compress(Bitmap.CompressFormat.JPEG, 100 , stream1);
Image myImg1 = Image.getInstance(stream1.toByteArray());
myImg1.setAlignment(Image.MIDDLE);
doc.add(myImg1);
Try following code:
/* Inserting Image in PDF */
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Bitmap bitmap = BitmapFactory.decodeResource(getBaseContext().getResources(), R.drawable.android);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100 , stream);
Image myImg = Image.getInstance(stream.toByteArray());
myImg.setAlignment(Image.MIDDLE);
//add image to document
doc.add(myImg);

iText style parsing HTML to PDF

I've a problem with iText.
I've followed this link: How to export html page to pdf format?
My snippet:
String str = "<html><head><body><div style=\"width:100%;height:100%;\"><h3 style=\"margin-left:5px;margin-top:40px\">First</h3><div style=\"margin-left:15px;margin-top:15px\"><title></title><p>sdasdasd shshshshdffgdfgd</p></div><h3 style=\"margin-left:5px;margin-top:40px\">The dream</h3><div style=\"margin-left:15px;margin-top:15px\"></div></div></body></head></html>";
String fileNameWithPath = "/Users/cecco/Desktop/pdf2.pdf";
com.itextpdf.text.Document document =
new com.itextpdf.text.Document(com.itextpdf.text.PageSize.A4);
FileOutputStream fos = new FileOutputStream(fileNameWithPath);
com.itextpdf.text.pdf.PdfWriter pdfWriter =
com.itextpdf.text.pdf.PdfWriter.getInstance(document, fos);
document.open();
document.addAuthor("Myself");
document.addSubject("My Subject");
document.addCreationDate();
document.addTitle("My Title");
com.itextpdf.text.html.simpleparser.HTMLWorker htmlWorker =
new com.itextpdf.text.html.simpleparser.HTMLWorker(document);
htmlWorker.parse(new StringReader(str.toString()));
document.close();
fos.close();
and work fine.
But tag style into h3 and div aren't considered.
But if I copy my html into http://htmledit.squarefree.com/ all is correct.
How can I solve this problem?
iText isn't the best Html Parser, but you can use Flying-Saucer for this. Flying-Saucer is build on top of iText but has a capable Xml / (X)Html parser. Short: Flying Saucer is perfect if you want html -> Pdf.
Here's how to generate the pdf from your string:
/*
* Note: i filled something in the title-tag and fixed the head tag (the whole body-tag was in the head)
*/
String str = "<html><head></head><body><div style=\"width:100%;height:100%;\"><h3 style=\"margin-left:5px;margin-top:40px\">First</h3><div style=\"margin-left:15px;margin-top:15px\"><title>t</title><p>sdasdasd shshshshdffgdfgd</p></div><h3 style=\"margin-left:5px;margin-top:40px\">The dream</h3><div style=\"margin-left:15px;margin-top:15px\"></div></div></body></html>";
OutputStream os = new FileOutputStream(new File("example.pdf"));
ITextRenderer renderer = new ITextRenderer();
renderer.setDocumentFromString(str);
renderer.layout();
renderer.createPDF(os);
os.close();
But: FS supports only valid Html / Xhtml / xml, so make shure it is.

get thumbnail of word in java using Apache POI

I study on a web sharing project in jsf.In this project users can upload documents such as .doc,.pdf,.ppt,..etc . I want show this documents first pages as a thumbnail. After some googling around I found Apache POI.Can anybody has any suggestion for my problem? How can I return thumbnail image of word doc's first page? I try this code.This code just get first picture that word doc contains:
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream("d:\\test.doc"));
HWPFDocument doc = new HWPFDocument(fs);
PicturesTable pt=doc.getPicturesTable();
List<Picture> p=pt.getAllPictures();
BufferedImage image=ImageIO.read(new ByteArrayInputStream(p.get(0).getContent()));
ImageIO.write(image, "JPG", new File("d:\\test.jpg"));
What's you are doing make nothing. HWPFDocument can extract thumbnail embedded in document (when saving files, check on 'add preview' option). So HWPFDocument can extract only thumbnail of documents having thumbnail.
Even, to do that, you have to make:
{code}
static byte[] process(File docFile) throws Exception {
final HWPFDocumentCore wordDocument = AbstractWordUtils.loadDoc(docFile);
SummaryInformation summaryInformation = wordDocument.getSummaryInformation();
System.out.println(summaryInformation.getAuthor());
System.out.println(summaryInformation.getApplicationName() + ":" + summaryInformation.getTitle());
Thumbnail thumbnail = new Thumbnail(summaryInformation.getThumbnail());
System.out.println(thumbnail.getClipboardFormat());
System.out.println(thumbnail.getClipboardFormatTag());
return thumbnail.getThumbnailAsWMF();
}
{code}
after that, you have to probably convert WMF file format to more common format (jpeg, png...). ImageMagick can help.

Categories

Resources