Содержание
- Unable to write to destination pdfkit python
- Error
- Relevant Code Snippet
- Other
- Setup File
- 1 Answer 1
- wkhtmltopdf попытке загрузки с HTTP, а не файл
- QPainter::begin(): Returned false Error: Unable to write to destination #2934
- Comments
- Footer
- Error unable to write to destination
Unable to write to destination pdfkit python
I am trying to use the package pdfkit (version 0.6.1 ) and wkhtmltopdf (version 0.12.6.0 ) to convert HTML to PDF.
I can use the script, until I try to convert it to an .exe file using cx_freeze . Then it fails. Using the executable, I get the following error:
Error
Relevant Code Snippet
Other
I searched on the internet and I found that the problem might be the destination path. But I am using the complete path: C:UsersDiegoDesktopJAA.pdf
Setup File
1 Answer 1
The diagnosis you made is correct (after all, Error: Unable to write to destination is pretty straightforward).
If you can create the output file, but the created EXE file cannot — and we know it couldn’t — then this means that either
- the real destination path is not actually there when the EXE runs. You think you’re writing to a given path, but somehow the EXE attempts to write elsewhere.
- the EXE has no permissions to create the file.
This might be caused by several reasons. The EXE file, for security reasons, might output in a given directory, so when you ask for «C:somefile», it actually tries to write in «%TEMP%/C:/somefile». Or might refuse to use a full path.
Or you could need to write the file in Unix syntax («C:/Users/. » instead of «C:Users. «, because e.g. «Diego» is translated to «0x0Diego» («iego» with a carriage return prefixed).
You should therefore insert into the EXE file some code to explore the filesystem the EXE is seeing (which might not be the same one you see!), and/or try to write to a different path, perhaps indeed %TEMP% (where permissions should be sufficient).
Источник
wkhtmltopdf попытке загрузки с HTTP, а не файл
Вот странная маленькая проблема, которая заставила меня опубликовать свой первый вопрос на SO. Я использую wkhtmltopdf для преобразования HTML-документа в PDF как часть приложения Rails. Для этого я рендерингу веб-страницу Rails в статический HTML-файл во временном каталоге, копирую статический верхний и Нижний колонтитулы и изображения в тот же временный каталог, а затем выполняю wkhtmltopdf с помощью «system».
Это прекрасно работает в среде разработки и тестирования. В моей постановке env, это не так. Я подозревал разрешения на во-первых, но первые две части этого процесса (создание статических HTML-файлов и копирование их в каталог) работают. Я могу запустить wkhtmltopdf из командной строки в этом временном каталоге и получить ожидаемый результат. Наконец, я запустил wkhtmltopdf через «system» и backticks через консоль Rails в промежуточной среде, и вот что я получаю в качестве вывода:
Обратите внимание на последний бит. Я указываю на локальные файлы, но он ищет их через http. Ладно, думаю я, может быть, я . нужно быть явным и передать ему файл: / / protocol, чтобы он не искал http. Поэтому я пытаюсь сделать следующее:
Обратите внимание, что это не удается со строчной буквой «l» в библиотеке. Какого черта? (И нет, это не становится лучше с рекомендацией игнорировать ошибку с этим переключателем.)
Есть идеи? Существует ли параметр Rails или Ruby, который вызывает перезапись системных команд? Есть ли опция, которую я могу добавить в wkhtmltopdf, чтобы убедиться, что он загружается из локального файла? Я совершенно сбит с толку. Спасибо!
Источник
QPainter::begin(): Returned false Error: Unable to write to destination #2934
When I run the executable wkhtmltopdf(linux) i got the error.
[stdout] =>
[stderr] => Loading pages (1/6)
[> ] 0%
[======> ] 10%
[==============================> ] 50%
[============================================================] 100%
QPainter::begin(): Returned false
Error: Unable to write to destination
Exit with code 1, due to unknown error.
The text was updated successfully, but these errors were encountered:
You probably specified a filename which it is unable to write the output.
i used «/usr/bin/wkhtmltopdf —encoding ‘UTF-8’ — -«. for proc_open in PHP.
same problem with stdout
Same error:
Loading pages (1/6)
QPainter::begin(): Returned false============================] 100%
Error: Unable to write to destination
Exit with code 1, due to unknown error.
use x64 on Windows 10
Any Solution for this?
wkhtmltopdf reported an error:
Loading pages (1/6)
[> ] 0%
[======> ] 10%
[============> ] 20%
[===================> ] 33%
[==============================> ] 50%
[============================================================] 100%
QPainter::begin(): Returned false
Error: Unable to write to destination
Exit with code 1, due to unknown error.
You probably specified a filename which it is unable to write the output.
Especificar la salida del archivo .pdf e.g. /home/user/Desktop/out.pdf
Make sure the target directory exists.
I got the same exact same error output as @Nagendra217.
In my case it could be solved by ensuring that the target directory exists.
Beforehand I had deleted the subdirectory where the pdf should be written. The error was resolved by creating it again.
In my opinion the «QPainter::begin(): Returned false» log line distracts from the real error cause.
I’ve had this exact problem and I had it multiple times. This happens especially when you have an automated system where you don’t know what kind of file names are being input. So in my case it happened with accented characters, forward slashes, especial symbols, spaces. none of these work. So before you send it to wkthtmltopdf to render PDF, make sure you replace characters.
So to summarize, the «Unable to write to destination», as it says, it always has to do with destination:
- As other Posts have mentioned, check destination folder is correct, privileges for that folder are correct.
- Check destination folder exists.
- Check name of the rendered file as I mentioned.
- Check if any options are set incorrectly, by just running wkhtmltopdf command without any options.
I was unable to write to my home directory on Windows 10 (using the x64 version). As a walkaround I created a C:out folder and added proper permissions.
@carkod I tested various unicode letters in the C:out directory. On some of them it worked ( á , æ , č , ň , ü ), on the others it threw an error ( α , þ , ø ).
I got the same error when running: pdfkit.from_url(current_url, filename) in a loop
OSError: wkhtmltopdf reported an error:
Loading pages (1/6)
QPainter::begin(): Returned false
Error: Unable to write to destination
Exit with code 1, due to unknown error.
In my case, there was a slash in the name of the input file.
the file name was: TCP/IP, which would mean IP is located inside TCP.
if in your case the files are meant to be in different directories: make sure the directory exists.
open CMD as Administrator
Any advice to solve this?
© 2023 GitHub, Inc.
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Источник
Error unable to write to destination
Шустрый
Профиль
Группа: Участник
Сообщений: 66
Регистрация: 9.7.2008
Репутация: нет
Всего: нет
SanLLIer |
|
||
|
pseud |
|
||
Экспёрт Тыдыщ Профиль Репутация: 10
Это сообщение отредактировал(а) pseud — 24.2.2010, 18:00 |
|||
|
Matematik |
|
||
Эксперт Профиль Репутация: 7
|
|||
|
chip_and_dayl |
|
||
Опытный Профиль Репутация: 1
|
|||
|
Шустрый
Профиль
Группа: Участник
Сообщений: 66
Регистрация: 9.7.2008
Репутация: нет
Всего: нет
SanLLIer |
|
||
|
chip_and_dayl |
|
||
Опытный Профиль Репутация: 1 |
|||
|
Шустрый
Профиль
Группа: Участник
Сообщений: 66
Регистрация: 9.7.2008
Репутация: нет
Всего: нет
SanLLIer |
|
||
|
Frees |
|
|||
Эксперт Профиль Репутация: 16
не храни ini рядом с ехе в висте это плохо. храни в предназначенном для этого мест — AppData Добавлено через 1 минуту и 36 секунд
|
||||
|
Эксперт
Профиль
Группа: Завсегдатай
Сообщений: 1839
Регистрация: 24.6.2008
Где: Россия, Тверь
Репутация: 29
Всего: 89
CodeMonkey |
|
||
|
pseud |
|
||||||
Экспёрт Тыдыщ Профиль Репутация: 10
не соглашусь. У меня всегда 2 ini. А почему? А потому что ехе лежит на расшареном только для чтения для всех ресурсе. Это дает возможность быстрого обновления.
1. Публиковать ссылки на вскрытые компоненты 2. Обсуждать взлом компонентов и делиться вскрытыми компонентами
Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, Snowy, MetalFan, bems, Poseidon, Rrader.
[ Время генерации скрипта: 0.1315 ] [ Использовано запросов: 21 ] [ GZIP включён ] Источник Adblock |
Вот странная маленькая проблема, которая заставила меня опубликовать свой первый вопрос на SO. Я использую wkhtmltopdf для преобразования HTML-документа в PDF как часть приложения Rails. Для этого я рендерингу веб-страницу Rails в статический HTML-файл во временном каталоге, копирую статический верхний и Нижний колонтитулы и изображения в тот же временный каталог, а затем выполняю wkhtmltopdf с помощью «system».
Это прекрасно работает в среде разработки и тестирования. В моей постановке env, это не так. Я подозревал разрешения на во-первых, но первые две части этого процесса (создание статических HTML-файлов и копирование их в каталог) работают. Я могу запустить wkhtmltopdf из командной строки в этом временном каталоге и получить ожидаемый результат. Наконец, я запустил wkhtmltopdf через «system» и backticks через консоль Rails в промежуточной среде, и вот что я получаю в качестве вывода:
> `wkhtmltopdf --footer-html tmp/invoices/footer.html --header-html tmp/invoices/header.html -s Letter -L 0in -R 0in -T 0.5in -B 1in tmp/invoices/test.html tmp/invoices/this.pdf`
Loading pages (1/6)
QPainter::begin(): Returned false ] 10%
Error: Unable to write to destination
Error: Failed loading page http://tmp/invoices/test.html (sometimes it will work just to ignore this error with --load-error-handling ignore) => ""
Обратите внимание на последний бит. Я указываю на локальные файлы, но он ищет их через http. Ладно, думаю я, может быть, я … нужно быть явным и передать ему файл: / / protocol, чтобы он не искал http. Поэтому я пытаюсь сделать следующее:
> system("wkhtmltopdf --footer-html file://Library/Server/Web/Data/Sites/intranet-staging/current/tmp/invoices/footer.html --header-html file://Library/Server/Web/Data/Sites/intranet-staging/current/tmp/invoices/header.html -s Letter -L 0in -R 0in -T 0.5in -B 1in file://Library/Server/Web/Data/Sites/intranet-staging/current/tmp/invoices/test.html file://Library/Server/Web/Data/Sites/intranet-staging/current/tmp/invoices/this.pdf")
Loading pages (1/6)
Error: Failed loading page file://library/Server/Web/Data/Sites/intranet-staging/current/tmp/invoices/test.html (sometimes it will work just to ignore this error with --load-error-handling ignore)
=> false
Обратите внимание, что это не удается со строчной буквой «l» в библиотеке. Какого черта? (И нет, это не становится лучше с рекомендацией игнорировать ошибку с этим переключателем.)
Есть идеи? Существует ли параметр Rails или Ruby, который вызывает перезапись системных команд? Есть ли опция, которую я могу добавить в wkhtmltopdf, чтобы убедиться, что он загружается из локального файла? Я совершенно сбит с толку. Спасибо!
Резюме
Я пытаюсь использовать пакет pdfkit
(версия 0.6.1
) и wkhtmltopdf
(версия 0.12.6.0
) для преобразования HTML в PDF.
Я могу использовать скрипт, пока не попытаюсь преобразовать его в файл .exe
с помощью cx_freeze
. Тогда это терпит неудачу. Используя исполняемый файл, я получаю следующую ошибку:
Ошибка
Exception in thread Thread-109:
Traceback (most recent call last):
File "C:UsersDiegoAppDataLocalProgramsPythonPython38-32libthreading.py", line 932, in _bootstrap_inner
self.run()
File "C:UsersDiegoAppDataLocalProgramsPythonPython38-32libthreading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "C:UsersDiegoPicturesZona PythonGuideMathsrcinterfazVentanaExportar.py", line 132, in __exportarHTMLaPDF
self.__resultado = self.__ctrl.exportarHTMLaPDF(
File "C:UsersDiegoPicturesZona PythonGuideMathsrccontroladorControlador.py", line 142, in exportarHTMLaPDF
return "E" if pdfkit.from_url(
File "C:UsersDiegoAppDataLocalProgramsPythonPython38-32libsite-packagespdfkitapi.py", line 26, in from_url
return r.to_pdf(output_path)
File "C:UsersDiegoAppDataLocalProgramsPythonPython38-32libsite-packagespdfkitpdfkit.py", line 156, in to_pdf
raise IOError('wkhtmltopdf reported an error:n' + stderr)
OSError: wkhtmltopdf reported an error:
Loading pages (1/6)
Warning: Javascript alert: Hola
QPainter::begin(): Returned false============================] 100%
Error: Unable to write to destination
Exit with code 1, due to unknown error.
Соответствующий фрагмент кода
pdfConf = pdfkit.configuration(wkhtmltopdf=os.path.join(
self.__principalPath, "docs/web/PDF/wkhtmltopdf.exe"))
pdfOpti = {
"window-status": "print",
"dpi": "90",
# "quiet": "",
"page-size": "A4",
"footer-html": f"{url}/footer.html"
}
try:
return "E" if pdfkit.from_url(
url=f"{url}/document.html",
output_path=outputPath,
configuration=pdfConf,
options=pdfOpti) else "F"
except:
return "F"
Другие
Я искал в Интернете и обнаружил, что проблема может заключаться в пути назначения. Но я использую полный путь: C:UsersDiegoDesktopJAA.pdf
Установочный файл
import sys
from cx_Freeze import setup, Executable
build_exe_options = {"packages": ["ctypes", "os", "wx", "json", "threading", "pdfkit"],
"excludes": ["tkinter"]}
base = None
if sys.platform == "win32":
base = "Win32GUI"
setup(name="App",
version="0.1",
description="",
options={"build_exe": build_exe_options},
executables=[Executable("main.py", base=base, icon="app.ico")])
1 ответ
Вы поставили правильный диагноз (в конце концов, Error: Unable to write to destination
довольно прост).
Если вы можете создать выходной файл, но созданный EXE-файл не может (а мы знаем, что не может), то это означает, что либо
- реальный путь назначения фактически отсутствует при запуске EXE. Вы думаете, что пишете по заданному пути, но каким-то образом EXE пытается записать куда-то еще.
- у EXE нет прав на создание файла.
Это может быть вызвано несколькими причинами. EXE-файл из соображений безопасности может выводиться в указанный каталог, поэтому, когда вы запрашиваете «C:somefile», он фактически пытается записать в «%TEMP%/C:/somefile». Или может отказаться использовать полный путь.
Или вам может понадобиться записать файл в синтаксисе Unix («C:/Users/…» вместо «C:Users…», потому что, например, «Diego» переводится как «0x0Diego» («iego» с префиксом возврата каретки).
Поэтому вам следует вставить в EXE-файл некоторый код для исследования файловой системы, которую видит EXE-файл (которая может отличаться от той, которую вы видите!), и/или попытаться напишите по другому пути, возможно, действительно %TEMP% (где разрешений должно быть достаточно).
0
LSerni
21 Апр 2021 в 21:38
**QPainter::begin(): Returned false============================] 100%
Error: Unable to write to destination
Exit with code 1, due to unknown error.**
def view_entry_pdf(request,id):
standard_fields = ['user_username','user_email', 'form_id', 'entry_id', 'date_dmy','user_full_name']
try:
entry = Entries.objects.get(pk=id)
cert = Certificate.objects.filter(form_id=entry.form.id, is_active=1).first()
get_cert = request.GET.get('cert_id','')
if get_cert:
cert = Certificate.objects.get(id=get_cert)
if not cert:
messages.warning(request, 'PDF template not found.')
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
valid_rules = validate_rules(entry,cert, cert.rules.all())
if valid_rules:
pass
else:
messages.warning(request, 'Certificate rules not matched.')
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
entry.is_read = True
entry.save()
file_name = 'entry-certificate.pdf'
if cert.file_name:
file_name = cert.file_name
res = re.findall(r'({{[^}]+}})', file_name)
placeholders = {}
standard_placeholders = {}
#standard_fields
for sf in standard_fields:
sfv = ''
if sf == 'user_username':
sfv = entry.user.username
elif sf == 'user_email':
sfv = entry.user.email
elif sf == 'form_id':
sfv = str(entry.form.id)
elif sf == 'entry_id':
sfv = str(entry.id)
elif sf == 'date_dmy':
today = datetime.now().date()
sfv = today.strftime("%d-%m-%Y")
elif sf == 'user_full_name':
sfv = f"{entry.user.first_name} {entry.user.last_name}"
standard_placeholders['{{'+sf+'}}'] = sfv
standard_placeholders = account_placeholders(request, standard_placeholders)
if res:
fields_all = entry.form.fields.all().order_by('sort_order')
for f in fields_all:
key = '{{'+f.label_name.replace(" ", "_").lower()+'}}'
placeholders[key] = f.id
for p in res:
f_id = placeholders.get(p)
if p and f_id:
en_data = entry.columns.filter(field_id=f_id)
val = ''
if en_data.count() and en_data[0].value:
val = en_data[0].value
file_name = file_name.replace(p, val)
elif standard_placeholders.get(p):
file_name = file_name.replace(p, standard_placeholders[p])
cert_path = '{}/form/certificates/{}'.format(settings.MEDIA_ROOT,file_name)
#cert_path = 'media/form/certificates/{file_name}'
url = '{}://{}/admin/forms/entry-pdf/{}?system_run=1&cert={}'.format(request.scheme, request.get_host(), entry.id, cert.id)
print("reached here------------------------------")
options = {
'dpi': 365,
'page-size':cert.page_type,
'orientation':cert.orientation
}
pdfkit.from_url(url,cert_path,options=options)
#set pdf permissions
setPdfPermissions(cert, cert_path)
return FileResponse(open(cert_path, 'rb'), content_type='application/pdf')
except FileNotFoundError:
raise Http404()
I am converting html to pdf. This code worked fine before. I dont know what kind of problem is arrising now. I am not aware of this tool htmltopdf. If i am doing anything wrong please help me
Back to Top