This is the qr-code generator, I put on String qrCodeData to try access the storage of my phone and open up a file, but it doesnt work. Turns out the generated qr code only gives the link.
public class QRCode {
public static void main(String[] args) {
try {
String qrCodeData = "Device storage/Download/japanese/Mastering_Kanji_1500.pdf";
String filePath = "D:\\QR code project\\Generated QR codes\\qr.png";
String charset = "UTF-8"; // or "ISO-8859-1"
Map < EncodeHintType, ErrorCorrectionLevel > hintMap = new HashMap < EncodeHintType, ErrorCorrectionLevel > ();
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
BitMatrix matrix = new MultiFormatWriter().encode(
new String(qrCodeData.getBytes(charset), charset),
BarcodeFormat.QR_CODE, 200, 200, hintMap);
MatrixToImageWriter.writeToFile(matrix, filePath.substring(filePath
.lastIndexOf('.') + 1), new File(filePath));
System.out.println("QR Code image created successfully! and stored at location"+filePath);
} catch (Exception e) {
System.err.println(e);
}
}
}
We are able to view and manipulate PDF files via the PDFBox library.
Android version.
We may also use MuPDF. It has an Android version.
Interpret the received link as a file or download it to storage, then proceed to interface with PDFBox library.
Note that file downloading and access on Android should now be done via Room interface or SQLite as recommended by Google.
Hope this helps.
Related
I want to download a file in my telegram bot code many tutorials say that I must use the getFile method that I can't find that in 4.2 version of the telegram API
so how I can download a file to a specific destination in host pc?
thanks
Assuming you are using TelegramBot SDK from rubenlagus (https://github.com/rubenlagus/TelegramBots), as I faced same issue. Below is my solution.
GetFile getFile = new GetFile().setFileId(fileId);
String filePath = execute(getFile).getFilePath();
File file = downloadFile(filePath, outputFile);
I had the same problem.
This was my solution. Not very nice but it works.
if (update.getMessage().hasDocument()){
String doc_id = update.getMessage().getDocument().getFileId();
String doc_name = update.getMessage().getDocument().getFileName();
String doc_mine = update.getMessage().getDocument().getMimeType();
int doc_size = update.getMessage().getDocument().getFileSize();
String getID = String.valueOf(update.getMessage().getFrom().getId());
Document document = new Document();
document.setMimeType(doc_mine);
document.setFileName(doc_name);
document.setFileSize(doc_size);
document.setFileId(doc_id);
GetFile getFile = new GetFile();
getFile.setFileId(document.getFileId());
try {
org.telegram.telegrambots.meta.api.objects.File file = execute(getFile);
downloadFile(file, new File("./data/userDoc/"+getID+"_"+doc_name));
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
Here I got this solution
enter link description here
I have been trying to scan QR code using zxing and primefaces
filename = getRandomImageName();
byte[] data = captureEvent.getData();
ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext()
.getContext();
String filePathToImage = servletContext.getRealPath("") + filename + ".jpeg";
FileImageOutputStream imageOutput;
try {
imageOutput = new FileImageOutputStream(new File(filePathToImage));
imageOutput.write(data, 0, data.length);
imageOutput.close();
String filePath = filePathToImage;
String charset = "UTF-8"; // or "ISO-8859-1"
Map hintMap = new HashMap();
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
String scannedDetails = readQRCode(filePath, charset, hintMap);
System.out.println("Data read from QR Code: " + scannedDetails);
RequestContext.getCurrentInstance().execute("PF('QRcodeDialog').hide();");
RequestContext.getCurrentInstance().update("baseTemplateForm:receiver");
} catch (IOException e) {
showMessage(Constants.SUCCESS_MESSAGE_ID, FacesMessage.SEVERITY_ERROR,
"QR code not scanned properly. Please scan again.", null);
throw new FacesException("Error in writing captured image.", e);
} catch (NotFoundException e) {
showMessage(Constants.MESSAGE_ID_FOR_QR, FacesMessage.SEVERITY_ERROR,
"QR code not scanned properly. Please scan again.", null);
} catch (CommandCenterException e) {
logger.error("Error in fetching receiver details");
}
What I want here is to continuously scan the image and detect QR code by itself instead of calling this function on click of a button.
p:photoCam
To continuously scan is not possible and not something you would like to do, keeping bandwidth and server load in mind. What you could do is use a p:poll to capture a photo once every few seconds. To save bandwidth play with the photoWidth, photoHeight and jpegQuality. Reduce them as far back as you can. Also, don't start the poll immediately, but at the start of a button click, and stop it as soon as you've received a QR code.
pe:codeScanner
From PrimeFaces Extension 10 and up you can use pe:codeScanner to scan QR codes. It's "live" and you can register an Ajax listener to send the scanned codes to a bean.
See:
Scan a QR code and decode it using p:photoCam
I'm trying to build a jsoup based java app to automatically download English subtitles for films (I'm lazy, I know. It was inspired from a similar python based app). It's supposed to ask you the name of the film and then download an English subtitle for it from subscene.
I can make it reach the download link but I get an Unhandled content type error when I try to 'go' to that link. Here's my code
public static void main(String[] args) {
try {
String videoName = JOptionPane.showInputDialog("Title: ");
subscene(videoName);
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
public static void subscene(String videoName){
try {
String siteName = "http://www.subscene.com";
String[] splits = videoName.split("\\s+");
String codeName = "";
String text = "";
if(splits.length>1){
for(int i=0;i<splits.length;i++){
codeName = codeName+splits[i]+"-";
}
videoName = codeName.substring(0, videoName.length());
}
System.out.println("videoName is "+videoName);
// String url = "http://www.subscene.com/subtitles/"+videoName+"/english";
String url = "http://www.subscene.com/subtitles/title?q="+videoName+"&l=";
System.out.println("url is "+url);
Document doc = Jsoup.connect(url).get();
Element exact = doc.select("h2.exact").first();
Element yuel = exact.nextElementSibling();
Elements lis = yuel.children();
System.out.println(lis.first().children().text());
String hRef = lis.select("div.title > a").attr("href");
hRef = siteName+hRef+"/english";
System.out.println("hRef is "+hRef);
doc = Jsoup.connect(hRef).get();
Element nonHI = doc.select("td.a40").first();
Element papa = nonHI.parent();
Element link = papa.select("a").first();
text = link.text();
System.out.println("Subtitle is "+text);
hRef = link.attr("href");
hRef = siteName+hRef;
Document subDownloadPage = Jsoup.connect(hRef).get();
hRef = siteName+subDownloadPage.select("a#downloadButton").attr("href");
Jsoup.connect(hRef).get(); //<-- Here's where the problem lies
}
catch (java.io.IOException e) {
System.out.println(e.getMessage());
}
}
Can someone please help me so I don't have to manually download subs?
I just found out that using
java.awt.Desktop.getDesktop().browse(java.net.URI.create(hRef));
instead of
Jsoup.connect(hRef).get();
downloads the file after prompting me to save it. But I don't want to be prompted because this way I won't be able to read the name of the downloaded zip file (I want to unzip it after saving using java).
Assuming that your files are small, you can do it like this. Note that you can tell Jsoup to ignore the content type.
// get the file content
Connection connection = Jsoup.connect(path);
connection.timeout(5000);
Connection.Response resultImageResponse = connection.ignoreContentType(true).execute();
// save to file
FileOutputStream out = new FileOutputStream(localFile);
out.write(resultImageResponse.bodyAsBytes());
out.close();
I would recommend to verify the content before saving.
Because some servers will just return a HTML page when the file cannot be found, i.e. a broken hyperlink.
...
String body = resultImageResponse.body();
if (body == null || body.toLowerCase().contains("<body>"))
{
throw new IllegalStateException("invalid file content");
}
...
Here:
Document subDownloadPage = Jsoup.connect(hRef).get();
hRef = siteName+subDownloadPage.select("a#downloadButton").attr("href");
//specifically here
Jsoup.connect(hRef).get();
Looks like jsoup expects that the result of Jsoup.connect(hRef) should be an HTML or some text that it's able to parse, that's why the message states:
Unhandled content type. Must be text/*, application/xml, or application/xhtml+xml
I followed the execution of your code manually and the last URL you're trying to access returns a content type of application/x-zip-compressed, thus the cause of the exception.
In order to download this file, you should use a different approach. You could use the old but still useful URLConnection, URL or use a third party library like Apache HttpComponents to fire a GET request and retrieve the result as an InputStream, wrap it into a proper writer and write your file into your disk.
Here's an example about doing this using URL:
URL url = new URL(hRef);
InputStream in = url.openStream();
OutputStream out = new BufferedOutputStream(new FileOutputStream("D:\\foo.zip"));
final int BUFFER_SIZE = 1024 * 4;
byte[] buffer = new byte[BUFFER_SIZE];
BufferedInputStream bis = new BufferedInputStream(in);
int length;
while ( (length = bis.read(buffer)) > 0 ) {
out.write(buffer, 0, length);
}
out.close();
in.close();
I am trying to work with Open Office in my Java app.
Based on SDK, with extra help from bootstrapconnector.jar I successfully started empty swritter and can write to the document.
Now, I would like to open document stored in ByteArray and after some modifications save changes doc to ByteArray.
Can somebody help me doing that, please?
Here is the SDK part starting sWritter.
public static com.sun.star.text.XTextDocument openWriter(
com.sun.star.uno.XComponentContext xContext) {
//define variables
com.sun.star.frame.XComponentLoader xCLoader;
com.sun.star.text.XTextDocument xDoc = null;
com.sun.star.lang.XComponent xComp = null;
try {
// get the remote office service manager
com.sun.star.lang.XMultiComponentFactory xMCF =
xContext.getServiceManager();
Object oDesktop = xMCF.createInstanceWithContext(
"com.sun.star.frame.Desktop", xContext);
xCLoader = (com.sun.star.frame.XComponentLoader) UnoRuntime.queryInterface(com.sun.star.frame.XComponentLoader.class,
oDesktop);
com.sun.star.beans.PropertyValue[] szEmptyArgs =
new com.sun.star.beans.PropertyValue[0];
String strDoc = "private:factory/swriter";
xComp = xCLoader.loadComponentFromURL(strDoc, "_blank", 0, szEmptyArgs);
xDoc = (com.sun.star.text.XTextDocument) UnoRuntime.queryInterface(com.sun.star.text.XTextDocument.class,
xComp);
} catch (Exception e) {
System.err.println(" Exception " + e);
e.printStackTrace(System.err);
}
return xDoc;
}
as you can see there is a method loadComponentFromURL.
I saw somewhere else, in the OOoBeanViewer, that it is possible to read and write doc to ByteArray, however I don't know how to achieve that without officebean.jar which I don't want to use in my project.
Thanks for your comments and hints.
I have 2 questions regarding PDFBox library (JAVA):
I have just started using PDFBox library and though it's working well, I couldn't
help noticing that it runs slower than ITEXT (the other pdf library I used) when
using ut.mergeDocuments() method (against concat_pdf.main(..) of ITEXT).
Does any one know if/how I can increase the performance of this tool?
I see that PDFBox is more sensitive to encrypted files. The ITEXT is allowing
me to do merge on encrypted PDF's but PDFBox is throwing an exception stating:
"PDFBoxConcat failedjava.io.IOException: Error: destination PDF is encrypted, can't append encrypted PDF documents."
Does any one know how come it works on ITEXT but not on PDFBox?
My guess is that the ITEXT is more sophisticated to know exactly what is encrypted
and allowing actions by that, while the PDFBox is just checking if it's encrypted or not.
Can anyone confirm this for me?
I have this code (open source) of pfdBox for the mergeDocuments() method where you can see the check for encryption:
if( destination.isEncrypted() )
{
throw new IOException( "Error: destination PDF is encrypted, can't append encrypted PDF documents." );
}
I tried to put this on remark but the merged document came out as gibberish.
Just adding some code examples of my attempts to improve performance.
These are the 3 different ways I tried to do this:
private static void PDFBoxConcat(String filePath) {
PDFMergerUtility ut = new PDFMergerUtility();
for (int i = 0; i < 50; i++) {
ut.addSource(filePath);
}
ut.setDestinationFileName("C:\\amdocs\\sensis\\dlv858\\pdfBox" + testNum + ".pdf");
try {
ut.mergeDocuments();
} catch (Exception e) {
System.out.println("PDFBoxConcat failed");
e.printStackTrace();
}
}
private static void PDFBoxConcat2(String filePath) {
String [] fileNamesArray = new String[51];
int i = 0;
for (i = 0; i < 50; i++) {
fileNamesArray[i] = filePath;
}
fileNamesArray[i] = "C:\\amdocs\\sensis\\dlv858\\pdfM" + testNum + ".pdf";
try {
PDFMerger.main(fileNamesArray);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void PDFBoxConcat3(String filePath) {
ArrayList<InputStream> list = new ArrayList<InputStream>();
PDFMergerUtility ut = new PDFMergerUtility();
for (int i = 0; i < 50; i++){
InputStream inputStream = new FileInputStream(filePath);
list.add(inputStream);
}
ut.addSources(list);
try {
ut.mergeDocuments();
} catch (Exception e) {
System.out.println("PDFBoxConcat failed");
e.printStackTrace();
}
}
Concerning your first question: Does any one know if/how I can increase the performance of this tool(= Apache PdfMergerUtility)?
The following setting helped me to reduce the merge time by ~ 75%:
pdfMergerUtility.setDocumentMergeMode(PDFMergerUtility.DocumentMergeMode.OPTIMIZE_RESOURCES_MODE);