I have an "export to word" feature in my application. It works perfectly. I use gridview's content exported into word file.
Now I want to add header/footer in exported word file which is generated from the below code:
Dim fileName As String = "Test_" & Format(DateTime.Now, "MMddyyyyhhmmss") & ".doc"
Dim sw As New StringWriter()
Dim w As New HtmlTextWriter(sw)
gvContent.RenderControl(w)
Dim content As String = sw.GetStringBuilder().ToString()
Response.Clear()
Response.AddHeader("Content-Disposition", "attachment; filename=" & fileName)
Response.Charset = ""
Response.ContentType = "application/vnd.ms-word"
Response.Write(finalContent)
Response.Flush()
Response.End()
Also the header & footer should be displayed in all pages of the word file, yust as when using Word's header/footer feature.
Is it possible? Does anyone have an idea for this?
What you're doing is actually creating an HTML file and giving it an extension that Word knows to open. You aren't creating a real .DOC file, but Word will recognize the HTML in and and display it.
I suspect that the flavor of HTML it's looking for is identical to the flavor it saves in. So I created a new document in Word 2013, added headers and footers, and saved it as an HTML file. After inspecting the HTML file, it appears that Word leaves those out. So I doubt that there is a way of specifying headers and footers in HTML files that it opens.
What you can do is switch to generating real MS Word files. These will have better support across various Word clients and Word-equivalents (such as Mac versions, mobile versions, and Libre Office).
Micrsoft provides a library for generating .DOCX files, called Open XML SDK. However, I've found that a bit hard to use.
I personally have used DocX a few times. Here's how you'd accomplish this with that library (code taken from this blog post):
C#
// Create a new document.
using (DocX document = DocX.Create(#"Test.docx"))
{
// Add Header and Footer support to this document.
document.AddHeaders();
document.AddFooters();
// Get the default Header for this document.
Header header_default = document.Headers.odd;
// Get the default Footer for this document.
Footer footer_default = document.Footers.odd;
// Insert a Paragraph into the default Header.
Paragraph p1 = header_default.InsertParagraph();
p1.Append("Hello Header.").Bold();
// Insert a Paragraph into the document.
Paragraph p2 = document.InsertParagraph();
p2.AppendLine("Hello Document.").Bold();
// Insert a Paragraph into the default Footer.
Paragraph p3 = footer_default.InsertParagraph();
p3.Append("Hello Footer.").Bold();
// Save all changes to this document.
document.Save();
}// Release this document from memory.
VB.NET (as translated by Telerik because I don't know VB.NET)
' Create a new document.
Using document As DocX = DocX.Create("Test.docx")
' Add Header and Footer support to this document.
document.AddHeaders()
document.AddFooters()
' Get the default Header for this document.
Dim header_default As Header = document.Headers.odd
' Get the default Footer for this document.
Dim footer_default As Footer = document.Footers.odd
' Insert a Paragraph into the default Header.
Dim p1 As Paragraph = header_default.InsertParagraph()
p1.Append("Hello Header.").Bold()
' Insert a Paragraph into the document.
Dim p2 As Paragraph = document.InsertParagraph()
p2.AppendLine("Hello Document.").Bold()
' Insert a Paragraph into the default Footer.
Dim p3 As Paragraph = footer_default.InsertParagraph()
p3.Append("Hello Footer.").Bold()
' Save all changes to this document.
document.Save()
End Using
' Release this document from memory.
Note that the above code was taken from a blog post written in 2010. The library is likely to have changed in the intervening six years.
Related
our product is Aspose.Words for .NET
I have read this link http://www.aspose.com/docs/display/wordsnet/Licensing
We had implemented the aspose license previously (by former developer) in our web application.
this is our code for extracting document .
Imports Aspose.Words
Imports System.IO
Public Class Converter
Public Shared Sub ConvertDocument(ByRef docPath As String, ByRef expPath As String)
Dim license As New Aspose.Words.License()
license.SetLicense("Aspose.Words.lic")
Dim info As Aspose.Words.FileFormatInfo = FileFormatUtil.DetectFileFormat(docPath)
Dim format As String = info.LoadFormat.ToString().ToLower()
If Not format = "pdf" Then
Dim doc As New Aspose.Words.Document(docPath)
doc.Save(expPath)
Else
' This object will help us generate the document.
Dim builder As New DocumentBuilder()
' You might need to specify a different encoding depending on your plain text files.
Using reader As New StreamReader(docPath, Encoding.UTF8)
' Read plain text "lines" and convert them into paragraphs in the document.
Dim line As String = Nothing
line = reader.ReadLine()
Do While line IsNot Nothing
builder.Writeln(line)
line = reader.ReadLine()
Loop
End Using
builder.Document.Save(expPath)
End If
End Sub
End Class
All the setup for aspose was done. After that our aspose license expired and we did not upgraded that for a while. Then we again applied for a temporary license for 30 days.
Now we have the new license for next one year. What do I have to do to apply the new license. Is it ok if I just replace the old licence file ( Aspose.Words.lic) with the new license file ( Aspose.Words.lic)
Or do I need to change anything in the XML file (Aspose.Words.xml) inside Bin folder as well.
You do not need to change anything in XML file or license file. If you're accessing the license from a file, you can simply replace the old file with the new one.
If you're using the license as an embedded resource, you can remove existing resource and then embed the new license file as a resource.
I hope this helps.
Disclosure: I work at Aspose.
I have a classic ASP page, and I need to create a loop for each row on a table and then create an html document and save it to the hard drive, but I want to create a template so I just send the two variables to the template so I don't have to write the HTML document each time on the loop.
This is what I have so far:
SQL = "select Title, Article from [ASPTest].[dbo].[articles]"
set rs = conn.execute(SQL)
arrRecs = rs.GetRows
For row = 0 To UBound(arrRecs, 2) 'Rows
For col = 0 To UBound(arrRecs, 1) 'Columns
Response.Write rs.Fields(col).Name & " = " & arrRecs(col, row) & " "
dim fs,f
set fs=Server.CreateObject("Scripting.FileSystemObject")
set f=fs.CreateTextFile("C:\Users\User\Documents\ASP Pages\"+arrRecs(col, row)+".html",true)
f.write("<html><body><div>It kinda works</div></body></html>")
f.close
set f=nothing
set fs=nothing
Next
Response.Write "<br />"
Next
Is there a way to use a template that has 2 variable holders and send the article name and title to the template and then save it to the disk?
Thank you.
I think you could probably achieve what you want using a template stored as a text file, and the Replace function.
Your template should be a fully-formed html page, but with placeholder values for the title and article. The placeholders need to be unique, so something like [[[~~~Title~~~]]] or a similar sequence that will not occur in your actual titles, articles, or the template itself.
<html>
<head><title>[[[~~~Title~~~]]]</title></head>
<body>
<h1>[[[~~~Title~~~]]]</h1>
<div id="article">[[[~~~Article~~~]]]</div>
</body>
</html>
In your code, read the template from the file and store it in a variable. (So technically, you could just write it to a variable in the first place, but VBScript is bad at string concatenation... anyway.) Get your array of titles & articles and loop through it (though only once: I'm not sure why you're looping through both rows and columns in your attempt). For each row, make a copy of the template, replace the title placeholder with the current row's title, replace the article placeholder with the current row's article, and write the result to a file.
Dim template, t
Dim fso, file
Dim rs, conn, SQL
Dim records, row
SQL = "SELECT ID, Title, Article FROM [ASPTest].[dbo].[articles]"
'[...database stuff...]
records = rs.GetRows
'[...close database...]
Set fso = Server.CreateObject("Scripting.FileSystemObject")
Set file = fso.OpenTextFile("path/to/template.txt",1) '- 1 = For reading
template = file.ReadAll
file.Close
Set file = Nothing
For row = 0 to UBound(records,2)
t = template
t = Replace(t,"[[[~~~Title~~~]]]",records(1,row))
t = Replace(t,"[[[~~~Article~~~]]]",records(2,row))
Set file = fso.CreateTextFile("path/to/html/" & records(0,row) & ".html")
file.Write(t)
file.Close
Set file = Nothing
Next
Set fso = Nothing
Back in the day I created the KudzuASP template engine to solve this rather complex deficiency in Classic ASP. In KudzuASP you can have ASP code pages that have absolutely NO HTML in them.
KudzuASP is as small include file roughly under 1000 lines of code that turns your hosting ASP page into an event driven object used by the template engine.
In short you create an instance of the template engine, set some variables, install custom code objects, and invoke it after which the template engine reads your template and make callbacks to your ASP page when and where appropriate. It has a library system so you can load libraries of custom tags handlers/components via code or by tags placed in your HTML template.
One of the best features is that for those still under the Classic ASP umbrella it makes 100% separation of application code and logic from presentation possible. Coding Classic ASP pages using KudzuASP is much easier than without and because of the way ASP compiles pages the callbacks are "native" and very fast.
You can find it here KudzuASP where the project is still maintained.
I have tow pages, first one for displaying the data in the text file and the other one is to store the data. I want to save a site in the text file but when i display the data will be just text and I can't click it as a link. The code I post is when I write to a file in display page.
Try
Dim fs As String
fs = Server.MapPath("Footer.txt")
lblsplittext.Text = ""
Dim filestream As StreamReader
filestream = New IO.StreamReader(fs)
Dim readcontents As String = filestream.ReadToEnd()
Dim textdelimiter As String = "#"
Dim splitout = Split(readcontents, textdelimiter)
Dim i As Integer
For i = 0 To UBound(splitout)
lblsplittext.Text &= splitout(i) & "<br>"
Next
filestream.Close()
Catch ex As Exception
Dim str As String
str = ex.Message
End Try
If you have a different suggestion about how to read from a file or database (it doesnt matter from where for now) just keep in mine when i display them i just need to have hyperlinks among my text... Or can I write to html file instead of text file if so what is the difference i need to make to write to html. I really really need help here and i have done many searches but i found nothing.
Thanks in advance.
There are a number of ways you could do this. One would be to use a series of dynamically-added Label controls. Your Hyperlink control could simply be inserted between one Label control and the next.
Do you intend to retrieve information from your series of labels on postback? (It would be redundant to do that, since you already know what the information is, but just in case.) Using multiple controls would make that more complicated. You could try one or more Literal controls, created dynamically and added as child controls to a Panel control. Again, the Hyperlink control would be added at whatever time you need it.
I've written an ASHX generic handler to output XML. However, for some reason, ASP.net is appending numerous whitespace characters to the end of the output which breaks the XML.
My code looks like this:
context.Response.ContentType = "text/xml";
XmlSerializer oSerializer = new XmlSerializer(typeof(ModelXml[]),new XmlRootAttribute("rows"));
System.IO.MemoryStream ms2 = new System.IO.MemoryStream();
System.Xml.XmlTextWriter tw = new System.Xml.XmlTextWriter(ms2,new System.Text.UTF8Encoding());
oSerializer.Serialize(tw,models);
string s = System.Text.Encoding.UTF8.GetString(ms2.GetBuffer());
tw.Close();
ms2.Close();
context.Response.Write(s.Trim());
context.Response.End();
When I run this code thru the debugger, I see that the string s does indeed contain the XML data with NO WHITESPACE. However, when I point Internet Explorer at this file, I get the following error:
The XML page cannot be displayed
Cannot view XML input using XSL style sheet. Please correct the error and then click the Refresh button, or try again later.
--------------------------------------------------------------------------------
Invalid at the top level of the document. Error processing resource 'http://localhost:5791/XXXXX.ashx'.
When I view the page source in Notepad, I see that the file begins with the correct XML, but there are numerous spaces appended to the end. If I remove these spaces, the XML file works fine with my browser and applications.
Why is ASP.net appending these spaces to my output and what can I do about it?
Switch from MS2.GetBuffer() to MS2.ToArray(). You are reading the buffer from the MemoryStream, which is preallocated for efficiency. You want just the used data, not the whole buffer.
Instead of serializing to a MemoryStream, you should serialize directly to Response.Output.
This should solve the issue.
I have some code that opens a word document using VBScript on an ASP.net page:
set objWord = CreateObject("Word.Application")
objWord.Visible = True
objWord.Documents.Open "c:\inetpub\wwwroot\JSWordTest\test.doc", False, False, False
This works great but opens the word doc in another window. Ideally I would like to make this look as if it is contained in the current page perhaps in an IFrame. I have some other buttons which paste text into the word document when clicked.
I cannot just set the src of the iframe to the word document as need a reference to the word document (objWord) to allow me to paste text into it in real time again using Vbscript to do this.
Not sure if this is possible but any ideas/alternatives welcome?
Requirements:
The word doc needs to be displayed from web browser
At the side of the word document will be some buttons which when clicked paste text into it
You can use this technique to get the contents of the Word document without displaying any windows at all.
' Declare an object for the word application '
Set objWord = CreateObject("Word.Application")
objWord.Visible = False ' Don''t show word '
objWord.Documents.open("C:\test.doc") ' Open document '
objWord.Selection.WholeStory ' Select everything in the doc '
strText = objWord.Selection.Text ' Assign document contents to var'
objWord.Quit False ' Close Word, don't save '
Once you've got the contents of the document in the variable you can do what you want with it as far as writing it out with a document.write or whatever method you want to use.
You can find more detail on the MS Word application object and its methods here: http://msdn.microsoft.com/en-us/library/aa221371(office.11).aspx
If it is an option to install an ActiveX component at the client machines, you can try EDraw Office Viewer component or the cheapter Ultra Office Control. Both are based on the DSOFramer example by Microsoft and provider similar methods to interface with the documents.
Sample code is given and shows how to trigger dialogs, insert text, etc.
You can get inspirations from Excel Viewer component. It is like EDraw Office Viewer but free and open source. Currently, it opens office documents only but you can easily change it to work with Word.
You could try saving to HTML format
Const wdFormatHTML = 8
dim doc
set doc = objWord.Documents.open("C:\test.doc")
doc.SaveAs "doc.htm", wdFormatHTML
' etc ...
and then use that as the source of your iframe document. Bear in mind that when saving to HTML format, Word creates a corresponding resources folder (for images etc), so you might need to take that into account.