How do I save an openJFX11 Canvas as a png/bitmap? - openjfx

Google is giving me a lot of old results for this (JavaFX). People point you at code using:
RenderedImage, SwingFXUtils and ImageIO
I have openJFX11 and it does not contain these libraries.
How can I save the canvas using built in JFX11 libraries?
My SaveUtil class using old libraries that can't be found:
public void saveCanvas(){
FileChooser fileChooser = new FileChooser();
//Set extension filter
FileChooser.ExtensionFilter extFilter =
new FileChooser.ExtensionFilter("png files (*.png)", "*.png");
fileChooser.getExtensionFilters().add(extFilter);
//Show save file dialog
File file = fileChooser.showSaveDialog(primaryStage);
if(file != null){
try {
WritableImage writableImage = new WritableImage(CANVAS_WIDTH, CANVAS_HEIGHT);
canvas.snapshot(null, writableImage);
RenderedImage renderedImage = SwingFXUtils.fromFXImage(writableImage, null);
ImageIO.write(renderedImage, "png", file);
} catch (IOException e) {
e.printStackTrace();
}
}
}

Related

Adding ColorSpace to resources causes the stream to close

I am trying very simple steps to add colorspace to resources using PDFBOX version 2.0.7, but it is not working.
I have PDF "pdf1.pdf", I am reading the colorspaces from this file and adding them to HashMap, then I am creating new resources and trying to add the colorspaces to the newly created resources. But it is not working
So the first Step, I read the colorSpaces from the sourcePdf file and add them to HashMap:
seperationColors = new HashMap<COSName, PDColorSpace>();
PDDocument sourcePdfFile = null;
try {
sourcePdfFile = PDDocument.load(new FileInputStream(new File(pdfPath)));
PDPage page = sourcePdfFile.getPages().get(0);
page.getContents();
for (COSName name : page.getResources().getColorSpaceNames()) {
PDColor color = page.getResources().getColorSpace(name).getInitialColor();
if (color.getColorSpace() instanceof PDSeparation) {
seperationColors.put(name, page.getResources().getColorSpace(name));
}
}
} catch (FileNotFoundException e) {
// e.printStackTrace();
} catch (IOException e) {
// e.printStackTrace();
} finally {
if (sourcePdfFile != null)
try {
sourcePdfFile.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
sourcePdfFile = null;
}
}
}
Then, at later stages in the code, I want to create new PDF document, and add the colorSpaces from the source Pdf to the new one.
PDResources newResources = new PDResources();
PDColorSpace colorSpace = originalDocumentColorSpaces.values().iterator().next();
newResources.add(colorSpace);
newResources will have the error: COSDictionary{COSStream has been closed and cannot be read. Perhaps its enclosing PDDocument has been closed?}
after the add operation (line 3)
colorSpace is of type PDSeperation.
Any clue?

Creating .doc on Google Drive

My goal is to programmatically create .doc on Google Drive with text and generated shapes.
My first problem that I cannot overcome is that when I create a doc file the file is generated saved on google drive but can not be opened .
Before when I created plain text files everything was OK.
private void createFile() {
final Task<DriveFolder> rootFolderTask = getDriveResourceClient().getRootFolder();
final Task<DriveContents> createContentsTask = getDriveResourceClient().createContents();
Tasks.whenAll(rootFolderTask, createContentsTask)
.continueWithTask(new Continuation<Void, Task<DriveFile>>() {
#Override
public Task<DriveFile> then(#NonNull Task<Void> task) throws Exception {
DriveFolder parent = rootFolderTask.getResult();
final Task<MetadataBuffer> Createlist = getDriveResourceClient().listChildren(parent);
DriveContents contents = createContentsTask.getResult();
OutputStream outputStream = contents.getOutputStream();
try (Writer writer = new OutputStreamWriter(outputStream)) {
writer.write("Witaj z nuclearhelperaa");
}
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle("test6")
// .setMimeType("text/plain")
.setMimeType("application/msword")
.setStarred(true)
.build();
return getDriveResourceClient().createFile(parent, changeSet, contents);
}
})
.addOnSuccessListener(this,
new OnSuccessListener<DriveFile>() {
#Override
public void onSuccess(DriveFile driveFile) {
showMessage(getString(R.string.file_created,
driveFile.getDriveId().encodeToString()));
finish();
}
})
.addOnFailureListener(this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.e(TAG, "Unable to create file", e);
showMessage(getString(R.string.file_create_error));
finish();
}
});
// [END create_file]
}
Is my task possible? I mean after creating a doc put some images formatted text and generated shapes (I need to create very simple picture containing couple dots) is possible to fulfil and if yes do you know some good libraries to make it possible?

Limiting upload file size in Playframework 2.2.x

Regarding file upload in play framework 2.2.3.
According to update on this question,
adding the following to application.conf should enable upload of files upto 10MB.
parsers.MultipartFormData.maxLength = 10240K
this does not work for me. I get "413, Request entity too large" error code for any file greater than 1MB.
I tried setting another field
parsers.text.maxLength=10M
Still upload fails with 413.
I upload files using XHR with a FormData that a can contain multiple files.
Upload Controller Code :
public Result uploadAttendeeFiles(){
try{
MultipartFormData body = request().body().asMultipartFormData();
List<FilePart> uploadedFiles = body.getFiles();
Map<String, String> returnMessages = new HashMap<String, String>();
String fileName ="", fileExtension="", fieldId = "";
int fileCounter = 0;
if (!CommonUtils.isEmpty(uploadedFiles)) {
for (FilePart filePar : uploadedFiles) {
try {
fileExtension = Files.getFileExtension(filePar.getFilename());
fieldId = body.asFormUrlEncoded().get("fieldId")[fileCounter];
fileName = body.asFormUrlEncoded().get("fileName")[fileCounter++];
InputStream in = new FileInputStream(filePar.getFile());
Object objectId = uploadService.loadFile(in, fileName, fileExtension);
if(objectId != null)
returnMessages.put(fieldId, objectId.toString());
else
returnMessages.put(fieldId, "failed-Failed to save file!");
} catch (IOException e) {
returnMessages.put(fileName+"."+fileExtension, "failed-Error while uploading file!");
e.printStackTrace();
}
}
}
else{
return ok("{\"errormessage\":\"No files selected!\"}");
}
return ok(Json.toJson(returnMessages));
} catch(Exception e) {
e.printStackTrace();
return ok("{\"errormessage\":\"Error while uploading files!\"}");
}
}

Adding new revision for document in DropBox through android api

I want to add a new revision to the document(Test.doc) in Dropbox using android api. Can anyone share me any sample code or links. I tried
FileInputStream inputStream = null;
try {
DropboxInputStream temp = mDBApi.getFileStream("/Test.doc", null);
String revision = temp.getFileInfo().getMetadata().rev;
Log.d("REVISION : ",revision);
File file = new File("/sdcard0/renamed.doc");
inputStream = new FileInputStream(file);
Entry newEntry = mDBApi.putFile("/Test.doc", inputStream, file.length(), revision, new ProgressListener() {
#Override
public void onProgress(long arg0, long arg1) {
Log.d("","Uploading.. "+arg0+", Total : "+arg1);
}
});
} catch (Exception e) {
System.out.println("Something went wrong: " + e);
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {}
}
}
New revision is created for first time. When i execute again, another new revision is not getting created.

How to display a pdf file using PDFBox in JPanel?

I have already created a JForm in netbeans which can read pdf file using PDFBox. But the problem is that I have used the method PDPage.convertToImage() which is really very slow. Can anyone please help me in displaying the pdf using PDFBox in the JPanel at a faster speed ?
The code I have written is inside an ActionListener for a JButton.
File f = null;
ArrayList<JLabel> jl = new ArrayList<JLabel>();
BufferedImage bi = null;
JFileChooser fc = new JFileChooser();
int x=fc.showOpenDialog(null);
if(x==JFileChooser.APPROVE_OPTION)
{
f=fc.getSelectedFile();
}
PDDocument doc=null;
try {
doc = PDDocument.load(f);
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, "not done\n"+ex);
}
List pages = doc.getDocumentCatalog().getAllPages();
Iterator itr = pages.iterator();
int q=0;
while(itr.hasNext())
{
PDPage page = (PDPage)itr.next();
try
{
bi = page.convertToImage();
q++;
jl.add(new JLabel(new ImageIcon(bi)));
}catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
}
itr = jl.iterator();
while(itr.hasNext())
{
viewPanel.setVisible(false);
viewPanel.add((JLabel)itr.next());
viewPanel.setVisible(true);
}
JOptionPane.showMessageDialog(null, "done");
NetBeans has several plugins to display PDFs
http://plugins.netbeans.org/plugin/5809/java-pdf-reader
http://plugins.netbeans.org/plugin/11676/netbeans-pdfviewer
http://plugins.netbeans.org/plugin/17/pdf-viewer-javafx-converter-and-bookmarking-application
HAve you tried any of them?