How to load a pdf file from Application Directory in flutter? - pdf

I am trying to load a PDF file from the application directory, I tried loading it from the url and it works and no I need to load the already downloaded PDF from the Application directory.
This is the package that I used to view PDF flutter_pdfview, while trying to load it from a url this works fine, now what I need is load an already downloaded pdf from the directory.
for loading file from directory i tried this:
var dir = await getApplicationDocumentsDirectory();
File file = File('${dir.path}/$pName.pdf');
bool fileExists = File(await '${dir.path}/$pName.pdf')
.existsSync();
if(fileExists)
{
urlPdfPath = file.toString();
print('url pdf path $urlPdfPath');
Navigator.push(context, MaterialPageRoute(builder: (context) {
return PdfViewer(
path: urlPdfPath,
product: pName,
);
}));
}
when i run this i got the exception
D/AndroidRuntime( 4565): Shutting down VM
E/AndroidRuntime( 4565): FATAL EXCEPTION: main
E/AndroidRuntime( 4565): java.lang.IllegalArgumentException: Unsupported value: java.io.FileNotFoundException: No such file or directory

In your Code:
Change - urlPdfPath = file.toString(); to urlPdfPath = file.path;

Related

Pdftk not working with Laravel on shared hosting

I am working on a project that needs a pdf form populated from a database my project is to develop on Laravel 9 and for pdf fill using mikehaertl/php-pdftk and this website is live on shared hosting. I am getting this error and am not able to solve this.
Error
Error: Unexpected Exception in open_reader()
java.lang.RuntimeException: java.lang.RuntimeException: error instantiating default socket factory: java.security.KeyManagementException: java.security.KeyStoreException: java.io.FileNotFoundException: /usr/lib/jvm/java-1.5.0-gcj-1.5.0.0/jre/lib/security/cacerts (No such file or directory)
at javax.net.ssl.SSLSocketFactory$ErrorSocketFactory.createSocket(libgcj.so.10)
at gnu.java.net.protocol.http.HTTPConnection.getSocket(libgcj.so.10)
at gnu.java.net.protocol.http.HTTPConnection.getOutputStream(libgcj.so.10)
at gnu.java.net.protocol.http.Request.dispatch(libgcj.so.10)
at gnu.java.net.protocol.http.HTTPURLConnection.connect(libgcj.so.10)
at gnu.java.net.protocol.http.HTTPURLConnection.getInputStream(libgcj.so.10)
at java.net.URL.openStream(libgcj.so.10)
at pdftk.com.lowagie.text.pdf.RandomAccessFileOrArray.(pdftk)
at pdftk.com.lowagie.text.pdf.RandomAccessFileOrArray.(pdftk)
at pdftk.com.lowagie.text.pdf.PRTokeniser.(pdftk)
at pdftk.com.lowagie.text.pdf.PdfReader.(pdftk)
at pdftk.com.lowagie.text.pdf.PdfReader.(pdftk)
Caused by: java.lang.RuntimeException: error instantiating default socket factory: java.security.KeyManagementException: java.security.KeyStoreException: java.io.FileNotFoundException: /usr/lib/jvm/java-1.5.0-gcj-1.5.0.0/jre/lib/security/cacerts (No such file or directory)
at javax.net.ssl.SSLSocketFactory.getDefault(libgcj.so.10)
at javax.net.ssl.HttpsURLConnection.getDefaultSSLSocketFactory(libgcj.so.10)
at javax.net.ssl.HttpsURLConnection.getSSLSocketFactory(libgcj.so.10)
...8 more
Caused by: java.security.KeyManagementException: java.security.KeyStoreException: java.io.FileNotFoundException: /usr/lib/jvm/java-1.5.0-gcj-1.5.0.0/jre/lib/security/cacerts (No such file or directory)
at gnu.javax.net.ssl.provider.SSLContextImpl.defaultTrustManager(libgcj.so.10)
at gnu.javax.net.ssl.provider.SSLContextImpl.engineInit(libgcj.so.10)
at javax.net.ssl.SSLContext.init(libgcj.so.10)
at javax.net.ssl.SSLSocketFactory.getDefault(libgcj.so.10)
...10 more
Caused by: java.security.KeyStoreException: java.io.FileNotFoundException: /usr/lib/jvm/java-1.5.0-gcj-1.5.0.0/jre/lib/security/cacerts (No such file or directory)
at gnu.javax.net.ssl.provider.X509TrustManagerFactory.engineInit(libgcj.so.10)
at javax.net.ssl.TrustManagerFactory.init(libgcj.so.10)
at gnu.javax.net.ssl.provider.SSLContextImpl.defaultTrustManager(libgcj.so.10)
...13 more
Caused by: java.io.FileNotFoundException: /usr/lib/jvm/java-1.5.0-gcj-1.5.0.0/jre/lib/security/cacerts (No such file or directory)
at gnu.java.nio.channels.FileChannelImpl.open(libgcj.so.10)
at gnu.java.nio.channels.FileChannelImpl.(libgcj.so.10)
at gnu.java.nio.channels.FileChannelImpl.create(libgcj.so.10)
at java.io.FileInputStream.(libgcj.so.10)
at java.io.FileInputStream.(libgcj.so.10)
at gnu.javax.net.ssl.provider.X509TrustManagerFactory.engineInit(libgcj.so.10)
...15 more
Error: Failed to open PDF file:
https://tax-ein-number.com/pdf/fss4.pdf
Errors encountered. No output created.
Done. Input errors, so no output created.
Here is the Laravel Controller code
use mikehaertl\pdftk\Pdf;
class FillAblePdfController extends Controller
{
public function autofillpdf_ss4(Request $request, $order_id)
{
$filename = 'pdf_'.rand(2000, 1200000).'.pdf';
$pdf = new Pdf(asset('/pdf/fss4.pdf'),[
'command' => public_path('/pdftk/bin/pdftk'),
'procEnv' => ['LD_LIBRARY_PATH' => public_path('pdftk/bin/libgcj.so.10')]
]);
$result = $pdf->fillForm([
'topmostSubform[0].Page1[0].f1_40[0]' => 'Jhon',
])->needAppearances()->saveAs(asset('pdf/'.$filename));
if ($result === false) {
echo $pdf->getError();
}
}
}
One important thing I have this code also tested in Core PHP (without Laravel Framework) on the same hosting and domain that is working fine but i need it in Laravel.
Core PHP code that works as I need
require_once 'vendor/autoload.php';
use mikehaertl\pdftk\Pdf;
$filename = 'pdf_'.rand(2000, 1200000).'.pdf';
$pdf = new Pdf('./fss4.pdf',['command' => './pdftk/bin/pdftk','procEnv' => ['LD_LIBRARY_PATH' => './pdftk/lib/libgcj.so.10']]);
$result = $pdf->fillForm([
'topmostSubform[0].Page1[0].f1_40[0]' => 'Ali'
])->needAppearances()
->saveAs('./pdf/'.$filename);
if ($result === false) {
echo $pdf->getError();
}
echo 'Your PDF is now generated, <a href="./pdf/'.$filename.'" download>Download it here</a>';

File upload checking REAL file mime type when uploading directly to S3

I'm using DropzoneJS to upload files directly to S3. When they add I file I am using my backend to check the mime type and create the S3 signature. When I say adding I file, I just means it's added it to the Dropzone queue so the file isn't uploaded yet it's just sending metadata about the file to the /upload/sign url.
this.on('addedfile', function (file) {
$.get('/upload/sign', {
name: file.name,
size: file.size,
type: file.type,
}).done(function (response) {
myDropzone.options.url = response.attributes.action;
file.additionalData = response.additionalData;
myDropzone.processFile(file);
}).fail(function (response) {
var data = JSON.parse(response.responseText);
myDropzone.emit('error', file, data);
});
});
This is all good! The problem is the file's mime type is only determined by the file extension, so I can happily rename a file from image.jpg to image.mp3 and file.type will be audio/mp3. This I guess is fine for browser warnings, but not if I want that mp3 to play or if I eventually want to process the audio!
Is there any way of telling the REAL mime type of the file, without having to pass the upload directly to the servers file system? I need to upload directly to S3 so passing it through an EC2 is not an option.

IncludeDirectory generate error Invalid file name for file monitoring

Code
var styleBundle = new StyleBundle("~/Content/Common") { Orderer = new FileBundleOrderer(server.MapPath("/Content/bundle.txt")) }
.IncludeDirectory("~/Content", "*.css", false);
Error message:
Invalid file name for file monitoring: '{ProjectPath}\Content'. Common
reasons for failure include:
- The filename is not a valid Win32 file name.
- The filename is not an absolute path.
- The filename contains wildcard characters.
- The file specified is a directory.
- Access denied.
'{ProjectPath}\Content' Content directory exist in project directory!!
Package version:
Microsoft.AspNet.Web.Optimi... 1.1.0

Unable to load SWF from application storage directory

While publishing my AIR application(CurrentFile), I have also included chatFile.swf with the installation files.
In my AIR settings panel [AIR 3.7 for Desktop], under 'Include Files' I have the following:
CurrentFile.swf
CurrentFile-app.xml
chatFile.swf
Here is the AS3 code in my CurrentFile.swf:
import flash.net.URLRequest;
import flash.events.Event;
import flash.display.Loader;
import flash.filesystem.File;
var chatLoaderWindow:Loader;
function loadchat(m:MouseEvent):void
{
chatLoaderWindow = new Loader();
chatLoaderWindow.contentLoaderInfo.addEventListener(Event.COMPLETE, chatLoadComplete);
chatLoaderWindow.contentLoaderInfo.addEventListener(Event.INIT, chatInitLoad);
chatLoaderWindow.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, chatErrorLoad);
chatLoaderWindow.contentLoaderInfo.addEventListener(HTTPStatusEvent.HTTP_STATUS, chatHttpStatus);
myclip.chatwindow.addChild(chatLoaderWindow);
var f:File = File.applicationStorageDirectory.resolvePath("chatFile.swf");
chatLoaderWindow.load(new URLRequest(f.url));
tracebox.text = "Chat URL" + f.url;
}
function chatLoadComplete(e:Event):void
{
tracebox.text = "chat loaded";
}
function chatErrorLoad(io:IOErrorEvent):void
{
tracebox.text = "chat IO Error: "+io;
}
function chatInitLoad(i:Event):void
{
tracebox.text = "chat INIT";
}
function chatHttpStatus(e:HTTPStatusEvent):void
{
tracebox.text = "chat Http"+e;
}
myclip.chatbut.addEventListener(MouseEvent.CLICK,loadchat);
/*
Output:
chat IO Error: [IOErrorEvent type="ioError" bubbles=false cancelable=false eventPhase=2 text="Error #2035" errorID=2035]
EDIT: I figured it out. It was really simple
This is not required:
var f:File = File.applicationStorageDirectory.resolvePath("chatFile.swf");
chatLoaderWindow.load(new URLRequest(f.url));
Insert this:
chatLoaderWindow.load(new URLRequest("app:/chatFile.swf"));
So now my question is:
What is the purpose of File.applicationStorageDirectory.resolvePath?
There are two directories here. One is the "application" directory, where your install files are placed. One is the "application-storage" directory, which is a convenient place to write files to at runtime. To access these directories you can either use the File.resolvePath() function or use the URI-scheme shortcuts, app: or app-storage:. In your initial attempt, you were just looking in the wrong directory for your file.
File.applicationStorageDirectory.resolvePath("somefile.swf").url will equal "app-storage:/somefile.swf"
File.applicationDirectory.resolvePath("somefile.swf").url will equal "app:/somefile.swf"
The application directory is where your app was installed. The app storage directory is a folder your app can save files to.
resolvePath() returns a file object. You can use it for purposes other than getting the cross-platform url for the file location, such as fileObj.exists and fileObj.parent.createDirectory(). fileObj.url is just the url you would use with URLLoader to access the file in a platform-independent manner.

Ckeditor searching for assets in root URI, while it's application is on sub URI

I've spent the past two days trying to fix this bug, but I really don't have anymore ideas or tools to solve it. I wonder if anyone here in stackoverflow can help me.
I'm trying to fix a website source code that uses the ckeditor gem. The ckeditor gem deliver a embedded web text editor. The problem is that the gem does not do it's job when the website is placed on a subdirectory. If the website is placed in the root directory like www.domain.com it works perfectly, but when I place it at a subdirectory, like www.domain.com/website, it does not show up the text editor.
The cause of not showing the editor is that the application try to find the assets of the ckeditor gem at the root directory of the server:
Failed to load resource: the server responded with a status of 404 (Not Found) http://domain.com/assets/ckeditor/config.js?t=C3HA5RM
Failed to load resource: the server responded with a status of 404 (Not Found) http://domain.com/assets/ckeditor/skins/kama/editor.css?t=C3HA5RM
Failed to load resource: the server responded with a status of 404 (Not Found) http://domain.com/assets/ckeditor/lang/pt-br.js?t=C3HA5RM
Failed to load resource: the server responded with a status of 404 (Not Found) http://domain.com/assets/ckeditor/plugins/embed/plugin.js?t=C3HA5RM
Failed to load resource: the server responded with a status of 404 (Not Found) http://domain.com/assets/ckeditor/plugins/attachment/plugin.js?t=C3HA5RM
When the right adress would be www.domain.com/website/assets/ckeditor/config.js?t=C3HA5RM
I've really searched over all the web trying to find the solution for this, but the only few similar situations that I found didn't provided me a solution.
In this Issue, at github, the user jronallo has the exactly same problem than me. But I tried to implement his solution but was not successful.
In this commit, at the ckeditor repository, the bug seems to be fixed, but even having this fix on my gem, (ckeditor 4.0.2 and rails 3.2.2) it keeps missing the assets on SubUri.
I've also tried manipulating the CKEDITOR_BASEPATH and the Ckeditor.relative_url, manually, but not succesfull again.
Does anyone have any idea about how can solve it? I would appreciate very much.
delete in your ckeditor config external plugins.
Failed to load resource: the server responded with a status of 404 (Not Found) http://domain.com/assets/ckeditor/plugins/embed/plugin.js?t=C3HA5RM
Failed to load resource: the server responded with a status of 404 (Not Found) http://domain.com/assets/ckeditor/plugins/attachment/plugin.js?t=C3HA5RM
And it's works!
My config:
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.editorConfig = function( config )
{
// Define changes to default configuration here. For example:
config.language = I18n.locale;
// config.uiColor = '#AADC6E';
/* Filebrowser routes */
// The location of an external file browser, that should be launched when "Browse Server" button is pressed.
config.filebrowserBrowseUrl = "/ckeditor/attachment_files";
// The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Flash dialog.
config.filebrowserFlashBrowseUrl = "/ckeditor/attachment_files";
// The location of a script that handles file uploads in the Flash dialog.
config.filebrowserFlashUploadUrl = "/ckeditor/attachment_files";
// The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Link tab of Image dialog.
config.filebrowserImageBrowseLinkUrl = "/ckeditor/pictures";
// The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Image dialog.
config.filebrowserImageBrowseUrl = "/ckeditor/pictures";
// The location of a script that handles file uploads in the Image dialog.
config.filebrowserImageUploadUrl = "/ckeditor/pictures";
// The location of a script that handles file uploads.
config.filebrowserUploadUrl = "/ckeditor/attachment_files";
// Rails CSRF token
config.filebrowserParams = function(){
var csrf_token = jQuery('meta[name=csrf-token]').attr('content'),
csrf_param = jQuery('meta[name=csrf-param]').attr('content'),
params = new Object();
if (csrf_param !== undefined && csrf_token !== undefined) {
params[csrf_param] = csrf_token;
}
return params;
};
config.addQueryString = function (url, params) {
var queryString = [];
if (!params)
return url;
else {
for (var i in params)
queryString.push(i + "=" + encodeURIComponent(params[ i ]));
}
return url + ( ( url.indexOf("?") != -1 ) ? "&" : "?" ) + queryString.join("&");
};
// Integrate Rails CSRF token into file upload dialogs (link, image, attachment and flash)
CKEDITOR.on('dialogDefinition', function (ev) {
// Take the dialog name and its definition from the event data.
var dialogName = ev.data.name;
var dialogDefinition = ev.data.definition;
var content, upload;
if ($.inArray(dialogName, ['link', 'image', 'attachment', 'flash']) > -1) {
content = (dialogDefinition.getContents('Upload') || dialogDefinition.getContents('upload'));
upload = (content == null ? null : content.get('upload'));
if (upload && upload.filebrowser['params'] == null) {
upload.filebrowser['params'] = config.filebrowserParams();
upload.action = config.addQueryString(upload.action, upload.filebrowser['params']);
}
}
});
/* Extra plugins */
// works only with en, ru, uk locales
// config.extraPlugins = "embed,attachment";
//for orfografii
config.disableNativeSpellChecker = false;
// config.removePlugins = 'contextmenu';
/* Toolbars */
config.toolbar = 'Mini';
config.toolbar_Mini =
[
['Source','-','Preview'],
['Cut','Copy','Paste','PasteText','PasteFromWord'],
['Undo','Redo','-','SelectAll','RemoveFormat'],
// ['Styles','Format'],
['Subscript', 'Superscript'],
// ['Subscript', 'Superscript', 'TextColor'],
// ['Maximize','-','About'],
['Bold','Italic','Underline'], ['NumberedList','BulletedList','-','Outdent','Indent','Blockquote']//,
// ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
// ['Link','Unlink','Anchor'], ['Image', 'Attachment', 'Flash', 'Embed'],
// ['Table','HorizontalRule','Smiley','SpecialChar','PageBreak']
];
config.toolbar = 'VeryEasy';
config.toolbar_VeryEasy =
[
['Source','-','Preview'],
['Cut','Copy','Paste','PasteText','PasteFromWord'],
['Undo','Redo','-','SelectAll','RemoveFormat'],
// ['Styles','Format'],
['Subscript', 'Superscript', 'TextColor'],
['Maximize','-','About'],
['Bold','Italic','Underline','Strike'], ['NumberedList','BulletedList','-','Outdent','Indent','Blockquote'],
// ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
// ['Link','Unlink','Anchor'], ['Image', 'Attachment', 'Flash', 'Embed'],
['Table','HorizontalRule','Smiley','SpecialChar','PageBreak']
];
config.toolbar = 'Easy';
config.toolbar_Easy =
[
['Source', '-', 'Preview'],
['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord'],
['Undo', 'Redo', '-', 'SelectAll', 'RemoveFormat'],
['Styles', 'Format'],
['Subscript', 'Superscript', 'TextColor'],
['Maximize', '-', 'About'],
'/',
['Bold', 'Italic', 'Underline', 'Strike'],
['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', 'Blockquote'],
['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'],
['Link', 'Unlink', 'Anchor'],
['Image', 'Attachment', 'Flash', 'Embed'],
['Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak']
];
config.jqueryOverrideVal = true;
};
I was having issues with ckeditor searching for skins on root dir because i was loading ckeditor.js dinamically after the whole page load.
The solution I've found in this thread
was to set the global var CKEDITOR_BASEPATH before the call to ckeditor.js.