Why PDFBox scan Fonts during Image Conversion (PDF to Png) - java

I am getting these a lot of times in my application
o.a.pdfbox.pdmodel.font.PDSimpleFont : No Unicode mapping for 28 (8) in font NSWQSF+TimesNewRoman,Bold
Because of this possibly my apllication is getting out of memory.
Can someone describe me why every page and all fonts in the pdf is kept in memory when using PDFBox pdf to image conersion?
My Code :
PDDocument document = null;
int pageCounter = 0;
try {
document = PDDocument.load(file);
document.setResourceCache(new PDFBoxResourceCache());
PDFRenderer pdfRenderer = new PDFRenderer(document);
pdfRenderer.setSubsamplingAllowed(true);
for (PDPage page : document.getPages()) {
ByteArrayOutputStream outputStream = null;
BufferedImage bufferedImage = null;
++pageCounter;
try {
bufferedImage = pdfRenderer.renderImageWithDPI(pageCounter - 1, 300, ImageType.RGB);
outputStream = new ByteArrayOutputStream();
ImageIOUtil.writeImage(bufferedImage, PAGE_FORMAT, outputStream);
} catch (IOException e) {
throw e;
} finally {
if (bufferedImage != null) {
bufferedImage.flush();
bufferedImage = null;
}
if (outputStream != null) {
try {
outputStream.close();
outputStream = null;
} catch (IOException ex) {
//
}
}
}
}
} catch (Exception e) {
throw e;
} finally {
if (document != null) {
document.close();
}
}
Cache
private class PDFBoxResourceCache extends DefaultResourceCache {
#Override
public void put(COSObject indirect, PDXObject xobject) {
// do nothing
}
}

Related

How to print document in Black and white using Monochrome option Mac OS?

I am unable to print pdf with MONOCHROME option on MAC, even
monochrome option is selected but still on MAC its printing in
COLOR but on windows its working fine for both options MONOCHROME and COLOR.
Plus, On MAC settings are disable even proper printer is connected.
but the same code running on windows its working fine in every
scenario.
I am using macOS High Sierra version 10.13.6
public boolean printFile(String fileUrl) {
PrintService[] printServicesAll = PrintServiceLookup.lookupPrintServices(null, null);
PrintService[] printServicesFiltered;
PrintRequestAttributeSet attrib = new HashPrintRequestAttributeSet();
Rectangle screen = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration().getBounds();
String OS = System.getProperty("os.name").toLowerCase();
attrib.add(new Copies(1));
attrib.add(new sun.print.DialogOnTop());
attrib.add(Chromaticity.MONOCHROME);
attrib.add(DialogTypeSelection.NATIVE);
PrintService selectedPrintService = null;
if (OS.contains("win")) {
if (printServicesAll.length > 0) {
printServicesFiltered = removeLogicalPrinters(printServicesAll);
selectedPrintService = ServiceUI.printDialog(null, screen.width / 3, screen.height / 3, printServicesFiltered, printServicesFiltered[0], null, attrib);
}
} else if (OS.contains("mac")) {
if (printServicesAll.length > 0) {
selectedPrintService = ServiceUI.printDialog(null, screen.width / 3, screen.height / 3, printServicesAll, printServicesAll[0], null, attrib);
}
}
if (attrib.get(Destination.class) != null) {
JOptionPane.showMessageDialog(null, "Print to file option not allowed!");
return false;
} else {
if (selectedPrintService != null)
System.out.println("selected printer: " + selectedPrintService.getName());
else
return false;
try {
DocPrintJob job = selectedPrintService.createPrintJob();
job.addPrintJobListener(new PrintJobAdapter() {
public void printDataTransferCompleted(PrintJobEvent event) {
System.out.println("data transfer complete");
}
public void printJobNoMoreEvents(PrintJobEvent event) {
System.out.println("received no more events");
}
});
print(selectedPrintService, fileUrl, attrib);
/*File file = new File(filePath);
Desktop.getDesktop().print(file);*/
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
Main Print File Method
private boolean print(PrintService printService, String fileUrl, PrintRequestAttributeSet attributes)
throws PrintException {
try {
PDDocument pdf = null;
String fileType = fileUrl.substring(fileUrl.lastIndexOf(".") + 1);
if (fileType.equalsIgnoreCase("bmp") || fileType.equalsIgnoreCase("gif") || fileType.equalsIgnoreCase("jpg") || fileType.equalsIgnoreCase("png")) {
try {
InputStream in = new URL(fileUrl).openStream();
PDDocument document = new PDDocument();
BufferedImage bImg = ImageIO.read(in);
float width = bImg.getWidth();
float height = bImg.getHeight();
PDPage page = new PDPage(new PDRectangle(width, height));
document.addPage(page);
PDImageXObject img = LosslessFactory.createFromImage(document, bImg);
PDPageContentStream contentStream = new PDPageContentStream(document, page);
contentStream.drawImage(img, 0, 0);
contentStream.close();
in.close();
pdf = document;
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintService(printService);
job.setPageable(new PDFPageable(pdf));
job.print(attributes);
pdf.close();
} catch (Exception e) {
e.printStackTrace();
}
} else if (fileType.equalsIgnoreCase("txt")) {
JEditorPane jEditorPane = new JEditorPane(fileUrl);
jEditorPane.print(null, null, false, printService, null, false);
} else if (fileType.equalsIgnoreCase("pdf")) {
pdf = PDDocument.load(new URL(fileUrl).openStream());
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintService(printService);
job.setPageable(new PDFPageable(pdf));
job.print(attributes);
pdf.close();
}
} catch (Exception e) {
throw new PrintException("Printer exception", e);
}
return true;
}

How to convert a file to pdf using pdfbox in java?

I want to extract all the content from a .docx or .txt file and then create a new pdf document which will contain the exact content. The problem is that I want to extract the content with the exact font style , if it's bolded or italic like so...This is what I've done so far:
public class Main {
public static void main(String[] args) {
JFileChooser fileChooser = new JFileChooser();
File file = null;
do {
int returnedValue = fileChooser.showOpenDialog(null);
if (returnedValue == JFileChooser.APPROVE_OPTION) {
file = fileChooser.getSelectedFile();
} else break;
} while (!file.getAbsolutePath().endsWith(".txt") &&
!file.getAbsolutePath().endsWith(".docx"));
Controller controller = new Controller();
controller.createPDF(file);
}
}
public class Controller {
public void createPDF(File file) {
String text = readFileContent(file);
System.out.println(text);
try {
newPdf(text, file);
} catch (IOException e) {
e.printStackTrace();
} catch (COSVisitorException e) {
e.printStackTrace();
} catch (FontFormatException e) {
e.printStackTrace();
}
}
private void newPdf(String text, File file) throws IOException, COSVisitorException, FontFormatException {
PDDocument doc = new PDDocument();
PDPage page = new PDPage();
doc.addPage(page);
PDPageContentStream contentStream = new PDPageContentStream(doc, page);
PDFont font = PDType1Font.COURIER;
contentStream.setFont(font, 14);
contentStream.beginText();
contentStream.setNonStrokingColor(Color.black);
contentStream.moveTextPositionByAmount(20, 750);
contentStream.drawString(text);
contentStream.endText();
contentStream.close();
doc.save("doc.pdf");
doc.close();
}
private String readFileContent(File file) {
String finalText = new String();
try {
FileReader fileReader = new FileReader(file.getAbsolutePath());
BufferedReader br = new BufferedReader(fileReader);
String line;
while ((line = br.readLine()) != null)
finalText += line;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return finalText;
}
}

making request spotify

I need help with getting information from spotify. How from this link : https://api.spotify.com/v1/search?q=Songs+of+Innocence&type=album
Can I take url:
"height" : 64,
"url" : "https://i.scdn.co/image/eb740cef5aa3d5e119baf868bdff2dbb5cc1a59b",
"width" : 64
And assign url to variable s in my code below:
public void getCover(String album) {
String query = "https://api.spotify.com/v1/search?q="+ encodeField(album)+"=album";
java.net.URL url = null;
try {
BufferedImage image = null;
url = new java.net.URL(query);
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
InputStream is = null;
try {
is = url.openStream();
} catch (IOException e) {
e.printStackTrace();
}
// get the text from the stream as lines
java.io.BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String s;
try {
s = reader.readLine()) // read link with image 64x64 resolution
} catch (IOException e) {
e.printStackTrace();
}
try {
//URL url2 = new URL("https://i.scdn.co/image/eb740cef5aa3d5e119baf868bdff2dbb5cc1a59b");
URL url2 = new URL(s);
image = ImageIO.read(url2);
ImageIcon icon = new ImageIcon(image);
jLabel2.setIcon(icon);
} catch (IOException e) {
e.printStackTrace();
}
}

How to compress tiff image

I am currently storing the tiff image in BufferredImage during runtime and displaying the same in image src tag of hmtl.
My tiff image size is about 60kb and currently it takes approx 1 sec time to load in web browser.
Is there any way to compress the tiff image or BufferedImage so that the time to load the image in browser can be faster.
Below is my code for saving tiff image in BufferredImage.
public BufferedImage savetiff(File srcFilePath) throws IOException {
FileSeekableStream stream = new FileSeekableStream(srcFilePath);
TIFFDecodeParam decodeParam = new TIFFDecodeParam();
decodeParam.setDecodePaletteAsShorts(true);
ParameterBlock params = new ParameterBlock();
params.add(stream);
RenderedOp image1 = JAI.create("tiff", params);
BufferedImage img = image1.getAsBufferedImage();
return img;
}
Code for converting tiff to image but in this code I have to save the jpeg image in disk and then I have to read it again. If there is any way to convert tiff to JPEG and save in BufferedImage.
public boolean tiff2JPG(File srcFilePath, File destFilePath) {
boolean status = false;
SeekableStream s = null;
RenderedImage op = null;
ImageDecoder dec = null;
TIFFDecodeParam param = null;
FileOutputStream fos = null;
JPEGEncodeParam jpgparam = null;
ImageEncoder en = null;
try {
s = new FileSeekableStream(srcFilePath);
dec = ImageCodec.createImageDecoder("tiff", s, param);
op = dec.decodeAsRenderedImage(0);
fos = new FileOutputStream(destFilePath);
jpgparam = new JPEGEncodeParam();
jpgparam.setQuality(67);
en = ImageCodec.createImageEncoder("jpeg", fos, jpgparam);
en.encode(op);
status = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.flush();
fos.close();
} catch (IOException io) {
// TODO Auto-generated catch block
io.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
return status;
Please advice.
Regards,
Dinesh Pise

jpegs are corrupted when resampled with java imageIO

The JPEG Images that ImageIO generated view correctly on windows file explorer, as well as safari webbrowser, but in FireFox, the resampled images are clipped.
How do I use ImageIO without corrupting the resamples?
The code should resize image keeping aspect ratio, as well as do jpeg compression, the convert it to a byte [] array, which could be written to a socket.
some of my code. in this snippet, I tried adding Jui library, but still the same issue.
public static BufferedImage imageistream;
public void Resample(String child,double width,double height) throws Exception, InvalidFileStructureException, InvalidImageIndexException, UnsupportedTypeException, MissingParameterException, WrongParameterException
{
String imagePath = "";
if(this.is_mac_unix == true)
{
imagePath = this.path+"/"+child;
}
else
{
imagePath = this.path+"\\"+child;
}
PixelImage bmp = null;
try {
bmp = ToolkitLoader.loadViaToolkitOrCodecs(imagePath, true, null);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Resample resample = new Resample();
resample.setInputImage(bmp);
double fixedRatio = width/height;
if(((double)bmp.getWidth()/bmp.getHeight()) >= fixedRatio)
{
resample.setSize((int)width,(int)(bmp.getHeight()/(bmp.getWidth()/width)));
}
else
{
resample.setSize((int)width,(int)(bmp.getWidth()/(bmp.getHeight()/height)));
}
resample.setFilter(Resample.FILTER_TYPE_LANCZOS3);
resample.process();
PixelImage scaledImage = resample.getOutputImage();
Processor.imageistream = ImageCreator.convertToAwtBufferedImage(scaledImage);
bmp = null;
Runtime rt = Runtime.getRuntime();
rt.gc();
}
...
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ImageIO.write(Processor.imageistream, "jpg", baos);
// ImageIO.write(Processor.imageistream, "png", baos); Works!
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte bytes[] = baos.toByteArray();
ByteArrayInputStream is = new ByteArrayInputStream(bytes);
OutputStream os = (OutputStream)obj[1];
OutputStreamWriter writer = (OutputStreamWriter)obj[0];
byte[] buf= new byte[4096];
int c;
try {
while (true) {
c= is.read(buf);
if (c<= 0) break;
os.write(buf, 0, c);
}
writer.close();
os.close();
is.close();
I've been successfully using:
BufferedImage bufferedImage = ImageIO.read(..);
Image img = bufferedImage.getScaledInstance(..);
BufferedImage result = // transform Image to BufferedImage
ImageIO.write(result, "image/jpeg", response.getOutputStream());
transformation is simply writing the contents of the image to a new BufferedImage

Categories