Save pictures in document using Powershell and Word 2013 - html

I'm trying to convert a HTML file with externally linked images to RTF using MS Word 2013 via Powershell commands, when using below command file gets converted however pictures are missing
$wrd = New-Object -ComObject "Word.Application"
$doc = $wrd.Documents.Open('c:\test.html')
$opt = [ref][Microsoft.Office.Interop.Word.WdSaveFormat]::WdFormatRTF
$name= [ref]'C:\test.rtf'
$wrd.ActiveDocument.SaveAs($name, $opt)
$wrd.ActiveDocument.Close()
$wrd.Quit()
If I do the conversion manually by opening the HTML file with Word and saving it as RTF same thing happens, no images, however if within Word I go to File, click on "Edit Links to File" and highlight all images, tick "Save picture in document" and then click on "Break Link" and then do the save as RTF, this time images are present within RTF (however with bad quality which is another issue..) [See picture below]
Is there a way to execute above process within Powershell?
Thanks

This does the job
$images = $doc.InlineShapes
foreach ($image in $images) {
$linkFormat = $image.LinkFormat
$linkFormat.SavePictureWithDocument = 1
$linkFormat.BreakLink()
}

Related

Displaying text from a text file in html

so i have a program that runs on a raspberry pi and outputs data to a text file. I'm wanting to try and display these outputs on a website i have already made.
so the goal is to have a text file (outputs.txt) and have the content from the text file be displayed on the website in the (outputs.txt(the text from the file)) tags
im going to be frank this probably makes no sense and made it even more confusing
html can't load any text file alone you need some server side language like php,java.net or javascript.In Php its very easy
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("webdictionary.txt"));
fclose($myfile);
?>
This will print the content of the file.

How to save a text as .txt file via a downloadable link?

HTML newbie here
I am working on an app using Streamlit. Based on the user inputs to the fields available, I am generating some data which I want to download in the form of a .txt file.
The data that I want to download is generated when I do
to_save = abc.serialize().encode("ascii", "ignore")
and when I do print(to_save), I get (this is just a small part of a very huge text data)
b"UNA:+.?
'UNB+UNOC:3+9978715000006:14+9978715000006:14+200529:1139+50582307060_WP?+_200101_200201++TL'UNH+1+MSCONS:D:04B:UN:2.3'BGM+7+50582307060_WP?+_200101_200201-1+9'DTM+137:202005291139:203'RFF+Z13:13008'NAD+MS+9978715000006::9'CTA+IC+:Michael
Jordan'COM+m.jordan#energycortex.com:EM'NAD+MR+9978715000006::9'"
Now, I want to save this information as a .txt file via an HTML link. I am following:
How to download a file in Streamlit
How to force fully download txt file on link?
and I have
reference = 50582307060_WP+_200101_200201
to_save = abc.serialize().encode("ascii", "ignore")
href = f'<a href="data:text/plain;charset=UTF-8,{to_save}" download={reference}.txt>Download File</a> (right-click and save as {reference}.txt)'
st.markdown(href, unsafe_allow_html=True)
But this doesn't work and shows as follows:
The start
The end
and when I do:
to_save = abc.serialize().encode("ascii", "ignore")
href = f'<a href="data:text/plain;charset=UTF-8" download={reference}.txt>Download File</a> (right-click and save as {reference}.txt)'
st.markdown(href, unsafe_allow_html=True)
I get
The problem with this being that the information that has to be saved as a .txt file (to_save = abc.serialize().encode("ascii", "ignore")) isn't being saved and I get a Failed-Network error
What is the mistake that I am doing and how can I enable saving the information stored in to_save (to_save = abc.serialize().encode("ascii", "ignore")) as an HTML downloadable link? Also, the file should be saved as 'reference.txt', with reference being defined as a variable above.
I reckon I have found a solution to your problem. Though I can't be entirely sure, it has two causes. The first one lies in the href attribute of the download link. The problem here is the " (double quotes) in the to_save variables data. The html, for what I could test with the by you provided data, renders it as follows:
<a href="data:text/plain;charset=UTF-8,b"UNA:+.? 'UNB+UNOC:3+9978715000006:14+9978715000006:14+200529:1139+50582307060_WP?+_200101_200201++TL'UNH+1+MSCONS:D:04B:UN:2.3'BGM+7+50582307060_WP?+_200101_200201-1+9'DTM+137:202005291139:203'RFF+Z13:13008'NAD+MS+9978715000006::9'CTA+IC+:Michael Jordan'COM+m.jordan#energycortex.com:EM'NAD+MR+9978715000006::9'"" download=filename.txt>Download File</a>
As you can see the value of the href attribute isn't all in the blue color (here in the stackoverflow code container above). That is because of the " that interrupt the string, it closes the earlier opened " after href=". In order to prevent this behaviour, you should replace the " in to_save with ". To the user this will look the same as " but the browser will treat it like a normal string.
You should add the following line of code to your python script to make that happen
to_save = abc.serialize().encode("ascii", "ignore")
#add this line:
to_save = to_save.replace('"','"')
Next the download attribute doesn't have any double quotes around it's value. It should, formally, look like this: download="filename.txt". Then again, for safety replace any possible"with"`.
The full python code should now look like this:
reference = 50582307060_WP+_200101_200201
reference = reference.replace('"','"')
to_save = abc.serialize().encode("ascii", "ignore")
to_save = to_save.replace('"','"')
href = f'Download File (right-click and save as {reference}.txt)'
st.markdown(href, unsafe_allow_html=True)
Hope this helps! If not, please comment.

Basic Image Uploader for CKEditor in WebPages in ASP.NET

I am using CKEditor in a web application in ASP.NET WebPages (Razor).
I spent a number of days trying to figure out how to make and integrate a basic file manager to support uploading images to CKEditor. The documentation in this area is next to useless. Nothing addressed the WebPages environment. Lots of PHP and WebForms and MVC, but nothing specifically for WebPages.
I finally figured out how to do it and am sharing it here.
CK Editor has an attribute that can be added to the .Replace which tells CKEditor to add an "Upload" tab (that had a built-in file browser) to the Image Properties panel:
CKEDITOR.replace('editor1'
, {
filebrowserImageUploadUrl: 'imageUpload2'
}
);
where "imageUpload2" was the name of the cshtml file (imageUpload2.cshtml) that contained the upload logic. Adding that filebrowserImageUploadUrl caused the CKEditor image properties panel to be modified to display (in the newly added "Upload" menu tab) a "Browse" button and a "Send to Server" button.
The "Browse" button activates CKEditor's Built-in file browser patterned after the html input filetype "file"; the "Send To Server" button executes the file manager you coded (see below).
The procedure would be for the user to:
click on the Insert Image icon in the CKEditor menu
Click on the "Upload" tab in the image properties dialog
Click on the "Browse" button to browse folders on the client machine and select ("Open") the desired image file
Click on the "Send to Server" button to execute the file manager's code (imageUpload2.cshtml), saving the image file to the folder specified in the cshtml file and passing the url of the file back to CKEditor.
The code in the file manager is minimal - no bells or whistles:
#{
Layout = null;
var context=HttpContext.Current;
HttpPostedFile uploads = context.Request.Files["upload"];
//get full filename
string file = System.IO.Path.GetFileName(uploads.FileName);
//get extension (including the period)
string ext = System.IO.Path.GetExtension(uploads.FileName);
//CKEditorFuncNum is passed in from the image propoerties panel in CKEditor
string CKEditorFuncNum = context.Request["CKEditorFuncNum"];
//use whatever folder name you prefer - make sure it has read/write permissions on the server
string url = Href("~/imageUploads/" + file);
var message = " .jpg .jpeg .gif .png ".Contains(ext.ToLower())?"":ext+" is invalid file type";
//Save file if it is one of the allowable extensions
if(String.IsNullOrEmpty(message))
{
uploads.SaveAs(context.Server.MapPath(".") + url );
}
//create return javascript to CKEditor (must have <script></script> tags)
var responseFormat = "<script>window.parent.CKEDITOR.tools.callFunction({0}, \"{1}\", \"{2}\");</script>";
var responseText = String.Format(responseFormat, CKEditorFuncNum, url, message);
//send script back to CKEditor image properties popup and close this page
context.Response.Write(responseText);
context.Response.End();
}
I hope this saves someone else the time I wasted trying to figure out what worked.

Create dynamic html file from code behind and open in a new window

I'm letting my users write their own HTML from my webpage.
When they click the preview button, my code behind needs access to controls on the page (and so I understand I can't use a web method here).
It builds the HTML and saves it as a file on the server.
My question is:
Once the file has been made, I want to automatically open the file in a new window for the user to see their handy work.
I'm using vb.net, but happy to receive c# answers.
Thanks folks !
.
.
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=--=-=-=--=-=-
Thank you very much Jan !!
I still have a slight problem though...
My code goes like this:
If fileExists Then
Do Until fileExists = False
tmpFormPreviewFileName = "Test" & GetRandomNumber() & ".html"
tmpFormPreviewFilePath = Server.MapPath("~") & "Pages\FormPreviews\" & tmpFormPreviewFileName
fileExists = My.Computer.FileSystem.FileExists(tmpFormPreviewFileName)
Loop
End If
My.Computer.FileSystem.WriteAllText(tmpFormPreviewFilePath, strHTML, False)
'Now open the file in a new window
btnPreview.OnClientClick = String.Format("window.open('/Pages/FormPreviews/{0}', 'myPopup', 'width=400,height=500')", tmpFormPreviewFileName)
So, the problem is - I don't know what the filename will be until after the user has clicked the preview button and the OnClientClick event won't fire until the user clicks the button for the 2nd time (which of course creates another HTML file)
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=--=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-
I'm still having problems getting the popup to work.
Here's my code at the moment:
'create a JavaScript command for opening the file in popup window
Dim strScript As String = String.Format("window.open('/Pages/FormPreviews/{0}, 'myPopup', 'width=400,height=500')", tmpFormPreviewFileName)
'register the JavaScript to be executed when web page loads
ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "openPopup", strScript, True)
ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "ShowMsg", "javascript:alert('Test Msg');", True)
My "ShowMsg" fires succesfully, but the line above it (the popup code) doesn't seem to work. Can you see what's going wrong at all ?
1) First you have to make the saved HTML files accessible through the web.
The simplest way is to save them to some subfolder of your website - e.g. let's create a "/GeneratedPages" folder.
When saving a file to this folder, you will need to construct a physical path to this folder. You can use the Server.MapPath method for it.
You will probably also have to set access rights to allow web application wrtting data to the folder.
2) Now let's implement opening of the preview window:
Assuming your Preview button is declared in your ASXP page as follows:
<asp:Button ID="btnPreview" runat="server" Text="Preview" />
Then you have just to add the following statement to code-behind, e.g. to the Page_Load method:
// sample name of one generate file
string pageName = "page1.html";
btnPreview.OnClientClick = string.Format("window.open('/GeneratedPages/{0}', 'myPopup', 'width=400,height=500')", pageName);
More information about the used window.open method can be found in Javascript reference, e.g. here.
UPDATE:
If are constructing the file just after clicking on the button (in a postback), then you can use a RegisterStartupScript method. Your server-side click handler for the preview button can be following:
protected void btnPreview_Click(object sender, EventArgs e)
{
string tmpFormPreviewFileName;
// construct the filename and save the file
// ...
// create a JavaScript command for opening the file in popup window
string script = string.Format("window.open('/Pages/FormPreviews/{0}, 'myPopup', 'width=400,height=500')", tmpFormPreviewFileName);
// registger the JavaScript to be executed when web page loads
ClientScript.RegisterStartupScript(GetType(), "openPupup", script, true);
}
I think your missing a quote in your JavaScript (see below)
Dim strScript As String = String.Format("window.open('/Pages/FormPreviews/{0}<-- here
Try this:
Dim strScript As String = String.Format("window.open('/Pages/FormPreviews/{0}', 'myPopup', 'width=400,height=500')", tmpFormPreviewFileName)

What do I have to do for opening and editing existing file with PHP?

I have different HTML files. I want to open, edit and then save changes with PHP (NOT OOP) in admin panel by using HTML textarea tag. What do I have to do for that? Do I need to create new mysql database? Could you please show me an example?
You can read the contents of the HTML file using file_get_contents:
$html = 'example.html';
$currentContents = file_get_contents($html);
// set the textarea text to $currentContents
To write the changes, you will have to post the textarea to a PHP script (through an HTML form) and then do something like:
$newContents = $_POST['textareaName'];
$html = 'example.html';
$fh = fopen($html, 'w') or die("File could not be opened.");
fwrite($fh, $newContents);
fclose($fh);
There are some security things you need to worry about it, but this is a basic example of how to achieve your goal. Good luck!
http://us.php.net/file_get_contents
http://us.php.net/fwrite