Convert DOC to PDF using DomPDF and PhpDocx - lumen

I am trying to convert .docx file to .pdf file by using dompdf and phpdocx. But I am getting error as -
file_put_contents(output_files/img6203609b73e9bc858.png): failed to open stream: No such file or directory {"exception":"[object] (ErrorException(code: 0): file_put_contents(output_files/img6203609b73e9bc858.png): failed to open stream: No such file or directory at C:\\xampp\\htdocs\\customer-api-2.0.1\\vendor\\phpdocx\\Classes\\Phpdocx\\Transform\\TransformDocAdvDOMPDF.php:478)
Here is my code -
require_once '../vendor/dompdf/dompdf/autoload.inc.php';
$docx = new \Phpdocx\Create\CreateDocx();
$path = storage_path('app');
$dompdf = new \Dompdf\Dompdf();
$transform = new \Phpdocx\Transform\TransformDocAdvDOMPDF($path.'\document.docx');
$transform->setDOMPDF($dompdf);
$transform->transform($path.'\document.pdf');
I am badly stuck here. Can anyone help me to resolve this error or suggest me any other alternative to achieve my aim

Related

Python3 Win32com Copy body of an email and paste to a new excel file

I'm trying to copy paste an html table received by outlook email to a new excel spreadsheet but I get a "pywintypes.com_error." Seeking a more pythonic way to do a the equivalent of a "Control+A" on an email body and paste to a new spreadsheet.
The relevant pieces of code are:
import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
# Select main Inbox
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
try:
for message in messages:
try:
if message.subject == 'myemailed Report':
print('Sender:' , message.sender)
print(message.subject)
mailItem = message.HTMLBody # <----Attempting to copy the body of the selected email.
# Start an instance of Excel
Xlsx = win32com.client.Dispatch("Excel.Application")
# Prevent Excel from asking questions.
Xlsx.DisplayAlerts = True # will change to False
Xlsx.Visible = True # will change to False
# Create a new Excel Workbook
workbook = Xlsx.Workbooks.Add()
ws = workbook.Sheets("Sheet1")
ws.Range('a7').select
ws.Paste(mailItem) # <--------------- Generates Error
workbook.SaveAs(mydesktop+'UpdatedSheet.xlsx')
# Quit Excel
Xlsx.Quit()
except:
x=1
except:
x=1
I get a message: Traceback (most recent call last):
File "", line 1, in
ws.Paste(mailItem)
File ">", line 3, in Paste
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', 'Paste method of Worksheet class failed', 'xlmain11.chm', 0, -2146827284), None)
Is there a better way? Help is appreciated!
ws.Paste(mailItem) is the main part of the problem. Code should be:
ws.Paste()
However - copying the email body as if hitting "Ctrl-A" is a little more involved and there are a lot of almost answers. I managed to get the following work but I don't know why it works.
I used import pyperclip which requires pip install pyperclip, along with the following code:
import pyperclip
def copy(text):
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardText(text, win32clipboard.CF_UNICODETEXT)
win32clipboard.CloseClipboard()
def paste():
win32clipboard.OpenClipboard()
data = win32clipboard.GetClipboardData(win32clipboard.CF_UNICODETEXT)
win32clipboard.CloseClipboard()
return data
Then later on...
mailItem = message.HTMLBody
pyperclip.copy(mailItem)
# Start an instance of Excel
Xlsx = win32com.client.Dispatch("Excel.Application")
# Create a new Excel Workbook
workbook = Xlsx.Workbooks.Add()
ws = workbook.Sheets("Sheet1")
ws.Range('a1').select
ws.Paste()
ws.Range('a1').select
workbook.SaveAs(myexcel.xlsx')
I tried doing this without using pyperclip but the combination of the two def's in the beginning and the ws.Paste() worked.

Save a file in a flask-wtf form to MongoDB's GridFS

I'm using the flask-user extension (https://flask-user.readthedocs.io/) along with the mongoengine adapter and flask-wtf to create an HTML form that'll accept several files (images, mp4). The goal is to directly store those files in MongoDB using GridFS but I can't get it to work without storing the image locally on the flask server first...
Here's my non-working code:
#bp.route('/video1', methods=['GET', 'POST'])
#login_required
def video1():
video1Form = Video1Form()
if request.method == 'POST' and video1Form.validate_on_submit():
newVideo1 = Video1(
slogan = video1Form.slogan.data,
objectif = video1Form.objectif.data,
stat1 = video1Form.stat1.data,
stat2 = video1Form.stat2.data
)
name = secure_filename(str(current_user.id) + "__" + "logo.png")
fh = open(video1Form.logo.data, 'rb')
newVideo1.logo.put(fh, filename=name, content_type = "image/jpeg")
newVideo1.save()
return redirect(url_for('video.download'))
if video1Form.errors:
flash(video1Form.errors, 'alert-danger')
return render_template('video/video1.html', video1Form=video1Form)
`
I get the following error on:
[...]File "/home/lucaspierru/Documents/IKADA/sos_sponsors/app/video/routes.py", line 35, in video1
fh = open(video1Form.logo.data, 'rb')
FileNotFoundError: [Errno 2] No such file or directory: 'name_of_the_uploaded_file.ext'
Is it possible to point directly to the file's content and not just get the filename without saving it to the server first ?
I found my mistake:
I forgot to add the enctype="multipart/form-data" attribute to my HTML <form> tag and apparently it is needed to properly upload files, otherwise they'll be considered as text data.

File upload Error : FlaskRestful - Getting 400 for POST request

I am trying to upload a file through the post request in flask restfulplus
I followed the example in this link
Here is my code
#ns.route('/upload/logo/')
#ns.doc('Upload Logo')
class UploadImage(Resource):
#ns.param('picture', 'image file path')
# #ns.route('/upload/')
def post(self):
parse = reqparse.RequestParser()
parse.add_argument('picture', type=FileStorage, location='files', required=True)
argsd = parse.parse_args()
print(argsd)
imgFile = argsd['picture']
print(imgFile)
imgFile.save("your_file_name.jpg")
return {'successfully' : 'loaded'}
For some reason the file is not getting uploaded. Can someone help me to solve this problem.
[Input Upload][2]
[2]: https://i.stack.imgur.com/BQc4W.png

How to solve this warning: failed to open stream: No such file or directory

Recently, I had a problem as:
Warning:include(C:\xampp\htdocs\crackverbal\application\views\errors\html\error_php.php): failed to open stream: No such file or directory in C:\xampp\htdocs\crackverbal\system\core\Exceptions.php on line 269
Warning: include(): Failed opening 'C:\xampp\htdocs\crackverbal\application\views\errors\html\error_php.php' for inclusion (include_path='.;C:\xampp\php\PEAR') in C:\xampp\htdocs\crackverbal\system\core\Exceptions.php on line 269
Warning: include(C:\xampp\htdocs\crackverbal\application\views\errors\html\error_php.php): failed to open stream: No such file or directory in C:\xampp\htdocs\crackverbal\system\core\Exceptions.php on line 269
Warning: include(): Failed opening 'C:\xampp\htdocs\crackverbal\application\views\errors\html\error_php.php' for inclusion (include_path='.;C:\xampp\php\PEAR') in C:\xampp\htdocs\crackverbal\system\core\Exceptions.php on line 269
I used Xampp and codeigniter-3.
I am guessing that
Under application\view\errors\html\ Folder, error_php.php file does not exist Or
Under application\view\ Folder, errors folder does not exist at all.
You can create dummy file and see if there is any error.
Under application/view/, create folder name errors,
then in errors folder, create folder name html
then in html folder, create php file name error_php.php
In error_php.php,
<?php echo "Sample text."; ?>
Just copy error folders in your codeigniter application to codeigniter view folder.
It will correct error page path. And the warnings will removed.
copy "errors" folder from "codeigniter3/application/views" and paste it into your project ("my_project/application/views").
Paste the below code into index.php
$view_folder = '';
// The path to the "views" folder
if ( ! is_dir($view_folder))
{
if ( ! empty($view_folder) && is_dir(APPPATH.$view_folder.DIRECTORY_SEPARATOR))
{
$view_folder = APPPATH.$view_folder;
}
elseif ( ! is_dir(APPPATH.'views'.DIRECTORY_SEPARATOR))
{
header('HTTP/1.1 503 Service Unavailable.', TRUE, 503);
echo 'Your view folder path does not appear to be set correctly. Please open the following file and correct this: '.SELF;
exit(3); // EXIT_CONFIG
}
else
{
$view_folder = APPPATH.'views';
}
}
if (($_temp = realpath($view_folder)) !== FALSE)
{
$view_folder = $_temp.DIRECTORY_SEPARATOR;
}
else
{
$view_folder = rtrim($view_folder, '/\\').DIRECTORY_SEPARATOR;
}
define('VIEWPATH', $view_folder);
You should download a fresh codeigniter folder and copy the error folder in the views folder.
Paste it in your own views folder.
please check your folder name may have a space like like: localhost/code igniter/welcome
I just copied "errors" folder from "codeigniter3/application/views" in newly unzipped codeigniter3 folder and paste it into my project ("my_project/application/views"). It solved the problem :)
Create application / view / folder,
in errors folder, create html folder
create php filename error_php.php in the html folder
Check the routs.php file in application>config/routs.php file and change $route['default_controller'] = 'welcome'
to
$route['default_controller'] = 'your default controller name';

imagick error: 'unable to open image' image upload

I get the following error when trying to process uploaded images with imagick.
Fatal error: Uncaught exception 'ImagickException' with message 'unable to open image `9eK59iu.jpg': No such file or directory # error/blob.c/OpenBlob/2644' in D:\PATH\upload.php on line 77
The code looks like this:
<?php
$new_folder_name = "D:/PATH/content";
mkdir("$new_folder_name",0700);
$tmp_img = $_FILES["upload_file"]["tmp_name"];
$img = new Imagick($tmp_img);
$img->thumbnailImage(100 , 100 , TRUE);
$img->writeImage($new_folder_name);
?>
Without imagick the image upload works just fine.
Only imagick won't open the image given to $_FILES
I also tried to open the image with imagick, after move_uploaded_file, like this:
<?php
$extension = pathinfo($upload_file_name, PATHINFO_EXTENSION);
$new_upload_file_name = rand(00000, 99999).".".$extension;
$new_folder_name = "D:/PATH/content".time();
mkdir("$new_folder_name",0700);
$path_to_file = $new_folder_name."/".$new_upload_file_name;
move_uploaded_file($_FILES["upload_file"]["tmp_name"],$path_to_file);
$img = new Imagick($path_to_file);
$img->thumbnailImage(100 , 100 , TRUE);
$img->writeImage($new_folder_name);
?>
neither works.. :-(
Any suggestion?
Read the file upload docs. The server-side temporary filename assigned by PHP to store the uploaded file in ['tmp_name'] in the $_FILES array. You're trying to use the client-side user-provided ['name'], which DOES NOT exist anywhere on your server.
$tmp_img = $_FILES["upload_file"]["tmp_name"];
^^^^
You are also simply assuming that the upload has succeed. That is NOT a good thing. Never EVER assume success with dealing with remote resources (web apis, file uploads, database operations, etc...). ALWAYS check for errors:
if ($_FILES['upload_file']['error'] !== UPLOAD_ERR_OK) {
die("Upload failed with error code " . $_FILES['upload_file']['error']);
}