Generate the MS word document in django
Import Necessary libraries Open Text file Clean Text file Generate Word cloud Save Word cloud Step 1: Import the necessary libraries Enter fullscreen mode Exit fullscreen mode The WordcCloud library is what generate the wordcloud. The module is used for file handling Step 2: Open the text file Enter fullscreen mode Exit fullscreen mode The function will open the text file using encoding, and returns content of file.
Generate the MS word document in django
Currently i am generating the reports in pdf format. But now i want to generate the reports in ms word or docx format.
def export_pdf(request,id): report = Report.objects.get(id=id) options1 = ReportPropertyOption.objects.filter(report=report,is_active=True) locations = [] out_string = "" map = None for option in options1: option.property = get_property_name(option.property) option.exterior_images = ReportExteriorImages.objects.filter(report = option) option.interior_images = ReportInteriorImages.objects.filter(report = option) option.floorplan_images = ReportFloorPlanImages.objects.filter(report = option) option.fitouts = ReportFitOut.objects.filter(propertyoption = option) if (option.gps_longitude): locations.append("&markers=color:red|label:S|"+""+str(option.gps_longitude)+","+str(option.gps_latidtude)+"") for loc in locations: out_string+=loc if locations: map = "http://maps.google.com/maps/api/staticmap?center=Bangalore&zoom=12&size=512x512&maptype=roadmap"+out_string+"&sensor=true" #map = "http://maps.google.com/maps/api/staticmap?zoom=12&size=400x400&maptype=roadmap&sensor=false¢er=\\" html = render_to_string('report/export.html', < 'pagesize' : 'A4', >, context_instance=RequestContext(request,)) result = StringIO.StringIO() pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), dest=result, link_callback=fetch_resources ) #pdf = Docx(StringIO.StringIO(html.encode("UTF-8")), dest=result, link_callback=fetch_resources ) if not pdf.err: return result else: return None
I am getting all the data in result and then exporting that data to pdf. But now i want to export the data to the docx or MS word format. The same result i want to export to docx format. As i am getting the data in pdf format so i dont want to convert that exported pdf to docx. I want to export directly in docx. I tried using python-docx, but not able to figure out how to export out in docx format. Can anyone guide me how to this. Which modul i should use in django. Please help me
Here is how I generate a docx file from within a Django view:
from docx import * from docx.shared import Inches def TestDocument(request): document = Document() docx_title="TEST_DOCUMENT.docx" # ---- Cover Letter ---- document.add_picture((r'%s/static/images/my-header.png' % (settings.PROJECT_PATH)), width=Inches(4)) document.add_paragraph() document.add_paragraph("%s" % date.today().strftime('%B %d, %Y')) document.add_paragraph('Dear Sir or Madam:') document.add_paragraph('We are pleased to help you with your widgets.') document.add_paragraph('Please feel free to contact me for any additional information.') document.add_paragraph('I look forward to assisting you in this project.') document.add_paragraph() document.add_paragraph('Best regards,') document.add_paragraph('Acme Specialist 1]') document.add_page_break() # Prepare document for download # ----------------------------- f = StringIO() document.save(f) length = f.tell() f.seek(0) response = HttpResponse( f.getvalue(), content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document' ) response['Content-Disposition'] = 'attachment; filename=' + docx_title response['Content-Length'] = length return response
Create word file (.doc) with python, A google for python generate word document lead to a lot of good results. It seems that either py docx or win32com.client are useful libraries. To read docx files with Word 2003 you have to install a plugin. py docx generates docx files, which are not (direct) compatible with word 2003.
Is it possible to edit doc files with Python?
I have a set of .doc files which I want to perform some simple changes to (e.g. set the font of all the text in each file to be arial).
I don’t want to do all the operations manually. I thought I’ll try to automate it with a Python script. Is it a complicated task? How is it done?
The Python docx module should be helpful.
(2nd time this question was asked today!)
How can I create a Word document using Python?, I’d like to create a Word document using Python, however, I want to re-use as much of my existing document-creation code as possible. I am currently using an XSLT to generate an HTML file that I programatically convert to a PDF file. However, my client is now requesting that the same document be made available in Word …
Generate Word Cloud using Python
Introduction
A word cloud (also called tag cloud or weighted list) is a visual representation of text data. Words are usually single words, and the importance of each is shown with font size or color. This article will discuss how to generate a Word Cloud using Python.
Input File
For the input file, you need a file that contains text. You can use a site like Project Gutenberg to find books that are available online. You can generate word clouds from famous books such as Alice in Wonderland by Lewis Carroll or Dracula by Bram Stoker. The possibilities are endless. This project used The Raven by Edgar Allan Poe. Simply copy the contents into a text file and save it in the same directory as the Python script.
Implementation
We need to write a function that will open this text file, iterate through the words, remove punctuation, and count the frequency of each word. We must also make sure to ignore word case, words that do not contain all alphabets, and common words like «and» or «the» . We will follow these 5 basic steps to implement the word cloud.
- Import Necessary libraries
- Open Text file
- Clean Text file
- Generate Word cloud
- Save Word cloud
Step 1: Import the necessary libraries
from wordcloud import WordCloud from collections import Counter import re import os
- The WordcCloud library is what generate the wordcloud.
- The Counter module is used to create a dictionary that will count the frequency of each word.
- The re module used to remove punctuations from the text file.
- The os module is used for file handling
Step 2: Open the text file
def get_file(filename): with open(filename, encoding='utf-8') as file_object: content = [word.lower().strip() for word in file_object] return ' '.join(content)
The get_file() function will open the text file using UTF-8 encoding, and returns content of file.
Step 3: Clean Text file
def clean_file(data): data = re.sub(r'[^\w\s]', '', data) stopwords = ('a', 'an', 'and', 'as', 'at', 'but', 'by', 'from', 'he', 'him', 'i', 'is', 'my', 'of', 'or', 'on', 'said', 'that', 'the', 'there', 'this', 'to', 'with') return Counter([word for word in data.split() if word not in stopwords])
The clean_file() function takes 1 parameter data which is the text file that will be passed to it. The re module is used to remove punctuation marks from the text. Additionally, any stopwords (i.e. commonly used words) will be removed as well. The results are returned in a Counter object which is used to count the frequency of the remaining words in the file.
Step 4: Generate Wordcloud
def generate_wordcloud(data): return WordCloud(height=800, width=1200).generate_from_frequencies(data)
The generate_wordcloud() function takes 1 parameter, data , which is the Counter object. It uses this word frequency hashmap to generate a Wordcloud image 800×1200 pixels in size. The result is the following Wordcloud image:
Step 5: Save Wordcloud
def save_wordcloud(data, filename): data.to_file(os.path.join(filename)) print(f'filename> has been successfully saved.')
Finally we want to save this Wordcloud image. The save_wordcloud() function takes two parameters, data and filename . data is the wordcloud object that will be saved, and filename is that name the file will be saved as.
Implementing the Code
def main(): # Get the path of the text file raven_path: str = os.path.join('the_raven.txt') # Open this text file: raven_file: str = get_file(raven_path) # Clean the text file: process_file: dict = clean_file(raven_file) # Generate wordcloud raven_cloud: [Wordcloud] = generate_wordcloud(process_file) # Save wordcloud image as 'raven_cloud.jpg' save_wordcloud(raven_cloud, 'raven_cloud.jpg') if __name__ == '__main__': main()
The Full Code
import os import re from collections import Counter from wordcloud import WordCloud def get_file(filename): with open(filename, encoding='utf-8') as fo: content = [i.lower().strip() for i in fo] return ' '.join(content) def clean_file(data): data = re.sub(r'[^\w\s]', '', data) stopwords = ('a', 'an', 'and', 'as', 'at', 'but', 'by', 'from', 'he', 'him', 'i', 'is', 'my', 'of', 'or', 'on', 'said', 'that', 'the', 'there', 'this', 'to', 'with') return Counter([word for word in data.split() if word not in stopwords]) def generate_wordcloud(data): return WordCloud(height=800, width=1200).generate_from_frequencies(data) def save_wordcloud(data, filename): data.to_file(os.path.join(filename)) print(f'filename> has been successfully saved.') def main(): raven_path = os.path.join('the_raven.txt') raven_file = get_file(raven_path) process_file = clean_file(raven_file) raven_cloud = generate_wordcloud(process_file) save_wordcloud(raven_cloud, 'raven_cloud.jpg') if __name__ == '__main__': main()
Conclusion
After reading this tutorial you should now be able to generate your own Wordcloud using Python. Use your imagination and have fun! Checkout the WordCloud for Python Documentation to learn more what you can do with this Python library. Please leave like or comment if you found this article interesting!
Ms word — how to create docx files with python, The previous answer is a good one, but there is another way: create the document in Word then hack the xml in Python to insert the content you want. I have done this several times. In fact, my current invoicing program works this way. Disadvantages: Conditional formatting and numbered lists will require some real …