How to convert a file to pdf using pdfbox in java? - 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;
}
}

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;
}

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

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
}
}

How I will display latest image to ImageView Another Activity?

My Application takes a picture from custom camera and save image to external storage.I save image by use code this.
SimpleDateFormat formatter = new SimpleDateFormat("dd_MM_yyyy_HH_mm", Locale.KOREA);
Date now = new Date();
String path = (Environment.getExternalStorageDirectory()+"/test"+".jpg");
String Newpath = (Environment.getExternalStorageDirectory()+"/"+"test_"+formatter.format(now)+".jpg");
Bitmap photo = BitmapFactory.decodeFile(path);
photo = Bitmap.createScaledBitmap(photo,480,640,false);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 70,bytes);
File f = new File(Newpath);
try {
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
File file = new File(path);
file.delete();
} catch (IOException e) {
e.printStackTrace();
}
example result > "test_13_12_2019_15_24" , "test_13_12_2019_15_26" , "test_13_12_2019_15_28"
It's time to now in external storage after take a picture but I want it show "test_13_12_2019_15_28" (latest picture) to imageView in another activity.
You can read your file like this.
public StringBuilder fromInternal(String filename) {
StringBuilder sb = new StringBuilder();
try {
FileInputStream fileInputStream = context.openFileInput(filename);
InputStreamReader inputStreamReader = new
InputStreamReader(fileInputStream, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sb;
}

merge audio and video file in android

i'm using mp4parser to merge audio and video files, here is below example i have tried but i'm getting null pointer exception at the very first line itself. i have kept audio and video files at desired location in my phone internal memory. if i debug, first line take lots of time & just halts after mins with null pointer error
try
{
H264TrackImpl h264Track = new H264TrackImpl(new FileDataSourceImpl("/mnt/sdcard/myvideo/video.mp4"));
AACTrackImpl aacTrack = new AACTrackImpl(new FileDataSourceImpl("/mnt/sdcard/myvideo/audio.acc"));
Movie movie = new Movie();
movie.addTrack(h264Track);
movie.addTrack(aacTrack);
Container mp4file = new DefaultMp4Builder().build(movie);
FileChannel fc = new FileOutputStream(new File("output.mp4")).getChannel();
mp4file.writeContainer(fc);
fc.close();
} catch (Exception ee)
{
Toast.makeText(this,ee.getMessage(),Toast.LENGTH_LONG).show();
}
whats wrong in my above code?
**Try this
I have follow few things to merge audio and video.
1)Capture Blank Video Dont use any audio source like
"mediaRecorder.setAudioSource(MediaRecorder.AudioSource.VOICE_RECOGNITION);"
2)save it to the sd card
3)it does not support MIME type=mp3.
4)so if we have to merge video and video. audio must be mp4 or aac
.**
5)call the method on button click or On Crete
String audiopath = "/sdcard/audio.m4a";
String videopath = "/sdcard/video.mp4";
String outputpath = "/sdcard/output.mp4";
mux(video, audio, output);
6)Main Code is here pass it only path where you store your video, audio(m4a,aac),Output path.
public boolean mux(String videoFile, String audioFile, String outputFile) {
Movie video;
try {
video = new MovieCreator().build(videoFile);
} catch (RuntimeException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
Movie audio;
try {
audio = new MovieCreator().build(audioFile);
} catch (IOException e) {
e.printStackTrace();
return false;
} catch (NullPointerException e) {
e.printStackTrace();
return false;
}
Track audioTrack = audio.getTracks().get(0);
video.addTrack(audioTrack);
Container out = new DefaultMp4Builder().build(video);
FileOutputStream fos;
try {
fos = new FileOutputStream(outputFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
}
BufferedWritableFileByteChannel byteBufferByteChannel = new BufferedWritableFileByteChannel(fos);
try {
out.writeContainer(byteBufferByteChannel);
byteBufferByteChannel.close();
Log.e("Audio Video", "11");
fos.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
private static class BufferedWritableFileByteChannel implements WritableByteChannel {
// private static final int BUFFER_CAPACITY = 1000000;
private static final int BUFFER_CAPACITY = 10000000;
private boolean isOpen = true;
private final OutputStream outputStream;
private final ByteBuffer byteBuffer;
private final byte[] rawBuffer = new byte[BUFFER_CAPACITY];
private BufferedWritableFileByteChannel(OutputStream outputStream) {
this.outputStream = outputStream;
this.byteBuffer = ByteBuffer.wrap(rawBuffer);
Log.e("Audio Video", "13");
}
#Override
public int write(ByteBuffer inputBuffer) throws IOException {
int inputBytes = inputBuffer.remaining();
if (inputBytes > byteBuffer.remaining()) {
Log.e("Size ok ", "song size is ok");
dumpToFile();
byteBuffer.clear();
if (inputBytes > byteBuffer.remaining()) {
Log.e("Size ok ", "song size is not okssss ok");
throw new BufferOverflowException();
}
}
byteBuffer.put(inputBuffer);
return inputBytes;
}
#Override
public boolean isOpen() {
return isOpen;
}
#Override
public void close() throws IOException {
dumpToFile();
isOpen = false;
}
private void dumpToFile() {
try {
outputStream.write(rawBuffer, 0, byteBuffer.position());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}

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();
}
}

Categories