How i can generate a content table in a pdf using wkhtml2pdf in a django application - django-templates

My goal is to generate a pdf in my django application, i would like to set a content table in the second page(page 2 of the pdf) using wkhtml2pdf,
I have add these new lines where i have put "2"(number of page where i want to display my content table) in the option --dump-default-toc-xsl, and i have put in the option (--dump-outline and -xsl-style-sheet) the file name of my html pdf that i want to render it to a pdf.
'--outline': True,
'--dump-outline':'/home/dev/.virtualenvs/django-projects/project1/templates/pages/generate_pdf.html',
'-xsl-style-sheet':'/home/dev/.virtualenvs/django-projects/project1/templates/pages/generate_pdf.html',
'--dump-default-toc-xsl':2,
this all the code in my settings.py
WKHTMLTOPDF_CMD = '/usr/local/bin/wkhtmltopdf'
WKHTMLTOPDF_CMD_OPTIONS = {
'quiet':True,
'disable-smart-shrinking':True,
'enable-local-file-access':True,
'page-size':'A4',
'margin-right':'0',
'margin-top':'15',
'margin-bottom':'10',
'margin-left':'3',
'encoding':"UTF-8",
#'--outline': None,
"zoom":1,
'javascript-delay':1000,
'footer-center':'[page]/[topage]',
"no-stop-slow-scripts":True,
'outline': True,
'dump-outline':'/home/dev/.virtualenvs/django-projects/project1/templates/pages/generate_pdf.html',
'xsl-style-sheet':'/home/dev/.virtualenvs/django-projects/project1/templates/pages/generate_pdf.html',
'dump-default-toc-xsl':2,
}
------> those lines that i have add generate me an error said:
CalledProcessError at /report/
Command '['/usr/local/bin/wkhtmltopdf', '----dump-default-toc-xsl', '2', '----dump-outline', '/home/dev/.virtualenvs/django-projects/project1/templates/pages/generate_pdf.html', '----outline', 'True', '---xsl-style-sheet', '/home/dev/.virtualenvs/django-projects/project1/templates/pages/generate_pdf.html', '--disable-smart-shrinking', '--enable-local-file-access', '--encoding', 'UTF-8', '--footer-center', '[page]/[topage]', '--javascript-delay', '1000', '--margin-bottom', '10', '--margin-left', '3', '--margin-right', '0', '--margin-top', '15', '--no-stop-slow-scripts', '--page-size', 'A4', '--quiet', '--zoom', '1', '/tmp/wkhtmltopdf3m5sidam.html', '-']' returned non-zero exit status 1.
Is it possible to generate a content table in a pdf using wkhtml2pdf in a django application!
any help will be appreciated am stuck on.thanks in advance.

Related

Not able to put tag column value on monday item

I am trying to use python to automation common Monday tasks. I am able to create an item in the board but the column (type=tag) is not updating.
I used this tutorial:
https://support.monday.com/hc/en-us/articles/360013483119-API-Quickstart-Tutorial-Python#
Here is my graphql code that I am executing:
query = 'mutation ($device: String!, $columnVals: JSON!) { create_item (board_id:<myboardid>, item_name:$device, column_values:$columnVals) { id } }'
vars = {'device': device,
'columnVals': json.dumps({
'cloud_name6': {'text': cloudname} # this is where i want to add a tag. cloud_name6 is id of the column.
})
}
data = {'query' : query, 'variables' : vars}
r = requests.post(url=apiUrl, json=data, headers=headers) print(r.json())
I have tried changing id to title as key in the Json string but no luck. I fetched the existing item and tried to add exact json string but still no luck. I also tried below json data without any luck
'columnVals': json.dumps({
'cloud_name6': cloudname
})
Any idea what's wrong with the query?
When creating or mutating tag columns via item queries, you need to send an array of ids of the tags ("tag_ids") that are relating to this item. You don't set or alter tag names via an item query.
Corrected Code
'columnVals': json.dumps({
'cloud_name6': {'tag_ids': [295026,295064]}
})
https://developer.monday.com/api-reference/docs/tags

How to get section heading of tables in wikipedia through API

How do I get section headings for individual tables: Xia dynasty (夏朝) (2070–1600 BC), Shang dynasty (商朝) (1600–1046 BC), Zhou dynasty (周朝) (1046–256 BC) etc. for the Chinese Monarchs list on Wikipedia via API? I use the code below to connect:
from pprint import pprint
import requests, wikitextparser
r = requests.get(
'https://en.wikipedia.org/w/api.php',
params={
'action': 'query',
'titles': 'List_of_Chinese_monarchs',
'prop': 'revisions',
'rvprop': 'content',
'format': 'json',
}
)
r.raise_for_status()
pages = r.json()['query']['pages']
body = next(iter(pages.values()))['revisions'][0]['*']
doc = wikitextparser.parse(body)
print(f'{len(doc.tables)} tables retrieved')
han = doc.tables[5].data()
doc.tables[6].data()
doc.tables[i].data() only return the table values, without its <h2> section headings. I would like the API to return me a list of title strings that correspond to each of the 83 tables returned.
Original website:
https://en.wikipedia.org/wiki/List_of_Chinese_monarchs
I'm not sure why you are using doc.tables when it is the sections you are interested in. This works for me:
for i in range(1,94,1):
print(doc.sections[i].title.replace('[[','').replace(']]',''))
I get 94 sections though rather than 83 and while you can use len(doc.sections) this will include See also etc. There must be a more elegant way of removing the wikilinks.

List of dictionarys to dataframe

im trying to make a dataframe out of a list of dictionaries. I am quite new at this whole programming thing, and google just makes me more confused. That is why i am turning to you guys hoping for some assistance.
The first two list values (YV01', '3nP3RFgGnBrOfILK4DF2Tp) i would like to have under columns called: Name and GlobalId. I would lie to drop Pset_wallcommon, AC_Pset_RenovationAndPhasing, and BaseQuantities. And use the rest of the keys(if that what they are called) as column names.
It would be great if someone could give me the right push :)
For the record: Im am parsing an Ifc file with the IfcOpenshell package
The data:
['YV01', '3nP3RFgGnBrOfILK4DF2Tp', {'Pset_WallCommon': {'Combustible': False, 'Compartmentation': False, 'ExtendToStructure': False, 'SurfaceSpreadOfFlame': '', 'ThermalTransmittance': 0.0, 'Reference': '', 'AcousticRating': '', 'FireRating': '', 'LoadBearing': False, 'IsExternal': False}, 'AC_Pset_RenovationAndPhasing': {'Renovation Status': 'New'}, 'BaseQuantities': {'Length': 13786.7314346, 'Height': 2700.0, 'Width': 276.0, 'GrossFootprintArea': 3.88131387595, 'NetFootprintArea': 3.88131387595, 'GrossSideArea': 37.9693748734, 'NetSideArea': 37.9693748734, 'GrossVolume': 10.4795474651, 'NetVolume': 10.4795474651}}, 'YV01', '1M4JyBJhXD5xt8fBFUcjUU', {'Pset_WallCommon': {'Combustible': False, 'Compartmentation': False, 'ExtendToStructure': False, 'SurfaceSpreadOfFlame': '', 'ThermalTransmittance': 0.0, 'Reference': '', 'AcousticRating': '', 'FireRating': '', 'LoadBearing': False, 'IsExternal': False}, 'AC_Pset_RenovationAndPhasing': {'Renovation Status': 'New'}, 'BaseQuantities': {'Length': 6166.67382573, 'Height': 2700.0, 'Width': 276.0, 'GrossFootprintArea': 1.6258259759, 'NetFootprintArea': 1.6258259759, 'GrossSideArea': 15.9048193295, 'NetSideArea': 15.9048193295, 'GrossVolume': 4.38973013494, 'NetVolume': 4.38973013494}}
all_walls = ifc_file.by_type('IfcWall')
wallList = []
for wall in all_walls:
propertySets = (ifcopenshell.util.element.get_psets(wall))
wallList.append(wall.Name)
wallList.append(wall.GlobalId)
wallList.append(propertySets)
print(wallList)
wall_table = pd.DataFrame.from_records(wallList)
print(wall_table)
I have tried these basic pd.DataFrame.from_dict/records/arrays(data)
but the output looks like this
enter image description here
UPDATE: Thank you so much for your help, i am learning alot from this!
So i made a dictionary out of the wallList, and flattened the dict. like this:
#list of walls
for wall in all_walls:
propertySets = (ifcopenshell.util.element.get_psets(wall))
wallList.append(wall.Name)
wallList.append(wall.GlobalId)
wallList.append(propertySets)
#dict from list
wall_dict = {i: wallList[i] for i in range(0, len(wallList))}
new_dict = {}
#flattening dict
for key, value in wall_dict.items():
if isinstance(value, dict):
for key in value.keys():
for key2 in value[key].keys():
new_dict[key + '_' + key2] = value[key][key2]
else:
new_dict[key] = value
wall_table = pd.DataFrame.from_dict(new_dict, orient='index')
print(wall_table)
It seems to work pretty good, the only problem is that the dataframe contains all walls, but only propertyset data from the first in the list. I cant seem to understand how the dict flattening loop works. I would also like the index names (Pset_WallCommon_Combustible, and so on) to be the columns in my dataframe. Is that possible?
enter image description here
EDIT : Simply flattening a list as i did goes nowhere. Actually, i think you should drop this list thing altogether and try to load the Dataframe from a dictionnary. We'd need to see what does all_walls look like to help you for that, tho.
Have you tried directly loading the all_walls dictionary into a dataframe : df = pd.Dataframe.from_dict(all_walls) ?
I think if that doesnt work, flattening the dictionnaries in a fashion similar to the following should do the trick.
new_dict = {}
for key, value in all_walls.items():
if isinstance(value, dict):
for key in value.keys():
for key2 in value[key].keys():
new_dict[key + '_' + key2] = value[key][key2]
else:
new_dict[key] = value

How can I increase the maximum file name size of attachments in Prestashop 1.7

On Prestashop 1.7, how can I increase the maximum file name size of attachments?
While naming attachment files in the Back Office, I encounter the following error message.
How can I go around this problem in Prestashop 1.7? I looked up online and found some solutions for Prestashop 1.5 or 1.6, but not for 1.7.
Here are some links that I followed:
https://www.prestashop.com/forums/topic/63332-bug-the-field-mime-is-too-long-32-chars-max/?tab=comments#comment-1189602
https://www.prestashop.com/forums/topic/81129-solvedhow-to-change-the-length-of-the-file-name-of-the-attachement/?tab=comments#comment-1197114
Following the above links, I have tried:
In the DB, changed the 'name' column's type in the 'ps_attachment_lang' table to 'varchar(128)'.
In Attachment.php (/classes/Attachment.php), made sure the size is 128.
'name' => ['type' => self::TYPE_STRING, 'lang' => true, 'validate' => 'isGenericName', 'required' => true, 'size' => 128],
In AdminProductsController.php (/controllers/admin/AdminProductsController.php), changed a part of function ajaxProcessAddAttachment(), from
if (!Validate::isGenericName($name)) {
$_FILES['attachment_file']['error'][] = $this->trans('Invalid name for %s language', [$language['name']], 'Admin.Notifications.Error');
} elseif (Tools::strlen($name) > 32) {
$_FILES['attachment_file']['error'][] = $this->trans('The name for %1s language is too long (%2d chars max).', [$language['name'], 32], 'Admin.Notifications.Error');
}
to
if (!Validate::isGenericName($name)) {
$_FILES['attachment_file']['error'][] = $this->trans('Invalid name for %s language', [$language['name']], 'Admin.Notifications.Error');
} elseif (Tools::strlen($name) > 64) {
$_FILES['attachment_file']['error'][] = $this->trans('The name for %1s language is too long (%2d chars max).', [$language['name'], 64], 'Admin.Notifications.Error');
}
But unfortunately, none of them worked.
Thanks in advance.
This is my own question but I found one solution.
In the AttachmentConstraint.php (in /src/Core/Domain/Attachment/Configuration/AttachmentConstraint.php), find the line
const MAX_NAME_LENGTH = 32;
and change it to whatever number that is lower than your database table can hold:
//const MAX_NAME_LENGTH = 32;
const MAX_NAME_LENGTH = 128; // this number needs to be lower than `name` column in `ps_attachment_lang` table
This should do the trick, but this solution requires changes in the core file. If there's anyone who knows a way we can achieve this without modifying the core files, please share that.

Html2pdf hindi support

I am using html2pdf in my Yii application to generate Pdf's, This is my code
Some 'Hindi' or 'Tamil' words are need to show in the pdf.
How can I get this?
sample code and generated Pdf are below, it shows either '?' or squares
$html2pdf = Yii::app()->ePdf->HTML2PDF();
$html2pdf = new HTML2PDF('L', 'A4', 'en');
$html2pdf->setDefaultFont('freesans');
$html2pdf->WriteHTML($this->renderPartial('attentancepdf', array(), true));
$html2pdf->Output($batch_name);
<span align="center"><h4><?php echo Yii::t('app','CLASS STUDENT ATTENDANCE'); ?></h4></span>
I have removed the "h4" tag then its worked , I dont know how!?
Also 'b' tag !!
<td width="150"><b><?php echo Yii::t('app','Batch'); ?></b></td>