I am in the process of converting Word doc standard equations (OMML) to MathML using flash or Flex, please help me out by providing simple Algorithm or code snippet.
Thanks in advance,
Mani
There is an XSLT 1 stylesheet that does that conversion provided by microsoft as part of the Word Distribution, it is what handles placing MathML on the clipboard in Word. Typically installed as something like
c:/Program Files (x86)/Microsoft Office/Office14/OMML2MML.XSL
There is some discussion of an early version of this at
http://dpcarlisle.blogspot.co.uk/2007/04/xhtml-and-mathml-from-office-20007.html
here is snippet of a C# class I was working on a few days ago ... I know it's too late .. but for less future pain.
I think it's not very different in Action Script
the file OMML2MML.xsl is located at %ProgramFiles%\Microsoft Office\Office12\ as mentioned by #David the xsl file is used for placing MathML on the clipboard in Word and converting OMML to MML too.
public static string OMML(string omml)
{
XslCompiledTransform xslTransform = new XslCompiledTransform();
xslTransform.Load("OMML2MML.xsl");
using (XmlReader reader = XmlReader.Create(new StringReader(omml)))
{
using (MemoryStream ms = new MemoryStream())
{
XmlWriterSettings settings = xslTransform.OutputSettings.Clone();
// Configure xml writer to omit xml declaration.
settings.ConformanceLevel = ConformanceLevel.Fragment;
settings.OmitXmlDeclaration = true;
XmlWriter xw = XmlWriter.Create(ms, settings);
// Transform our OfficeMathML to MathML
xslTransform.Transform(reader, xw);
ms.Seek(0, SeekOrigin.Begin);
StreamReader sr = new StreamReader(ms, Encoding.UTF8);
string MathML = sr.ReadToEnd();
return MathML;
}
}
}
Related
I've an IFormFile image file (from postman as form data), which I convert into byte array. Before converting it into byte array, I want to rotate it into its actual position (if user input image as 90°(right). I'm implementing web api in asp.net core 2.0.
byte[] ImageBytes = Utils.ConvertFileToByteArray(model.Image);
public static byte[] ConvertFileToByteArray(IFormFile file)
{
using (var memoryStream = new MemoryStream())
{
file.CopyTo(memoryStream);
return memoryStream.ToArray();
}
}
Any help, Thanks in advance.
In my project I need to crop and resize the images users upload. And I am using a fantastic library called ImageSharp from Six Labors. You can use its image processor to do the transformation such as Resize, Crop, Skew, Rotate and more!
Install via NuGet
I am actually using their nightly build through MyGet.
Visual Studio -> Tools -> Options -> NuGet Package Manager -> Package Sources
Hit the "Plus" button to add a new package resource
I typed "ImageSharp Nightly" as the name and put "https://www.myget.org/F/sixlabors/api/v3/index.json" as the source url.
On Browse, search "SixLabors.ImageSharp" (In my case I also need "SixLabors.ImageSharp.Drawing" but in your case you might only need to core library. Always refer back to their documentations).
Crop & Resize
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats;
using SixLabors.ImageSharp.Processing;
using SixLabors.ImageSharp.Processing.Transforms;
using SixLabors.Primitives;
using System.IO;
namespace DL.SO.Project.Services.ImageProcessing.ImageSharp
{
public CropAndResizeResult CropAndResize(byte[] originalImage,
int offsetX, int offsetY, int croppedWidth, int croppedHeight,
int finalWidth, int finalHeight) : IImageProcessingService
{
IImageFormat format;
using (var image = Image.Load(originalImage, out format))
{
image.Mutate(x => x
// There is .Rotate() you can call for your case
.Crop(new Rectangle(offsetX, offsetY, croppedWidth, croppedHeight))
.Resize(finalWidth, finalHeight));
using (var output = new MemoryStream())
{
image.Save(output, format);
// This is just my custom class. But see you can easily
// get the processed image byte[] using the ToArray() method.
return new CropAndResizeResult
{
ImageExtension = format.Name,
CroppedImage = output.ToArray()
};
}
}
}
}
Hope this helps you - from a big fan of ImageSharp library!
Magick.NET, The ImageMagick wrapper for .Net Core can be used for many file manipulations, see https://github.com/dlemstra/Magick.NET
byte[] byt = System.IO.File.ReadAllBytes(filePath);
System.IO.MemoryStream ms = new System.IO.MemoryStream(byt);
using (Image img = Image.FromStream(ms))
{
RotateFlipType r = angle == 90 ? RotateFlipType.Rotate90FlipNone : RotateFlipType.Rotate270FlipNone;
img.RotateFlip(r);
img.Save(filePath);
}
Using your existing code you can do the following
My requirement is to use Web API to send across the network, a zip file (consisting a bunch of files in turn) which should not be written anywhere locally (not written anywhere on the server/client disk). For zipping, I am using DotNetZip - Ionic.Zip.dll
Code at Server:
public async Task<IHttpActionResult> GenerateZip(Dictionary<string, StringBuilder> fileList)
{
// fileList is actually a dictionary of “FileName”,”FileContent”
byte[] data;
using (ZipFile zip = new ZipFile())
{
foreach (var item in filelist.ToArray())
{
zip.AddEntry(item.Key, item.Value.ToString());
}
using (MemoryStream ms = new MemoryStream())
{
zip.Save(ms);
data = ms.ToArray();
}
}
var result = new HttpResponseMessage(HttpStatusCode.OK);
MemoryStream streams = new MemoryStream(data);
//, 0, data.Length-1, true, false);
streams.Position = 0;
//Encoding UTFEncode = new UTF8Encoding();
//string res = UTFEncode.GetString(data);
//result.Content = new StringContent(res, Encoding.UTF8, "application/zip");
<result.Content = new StreamContent(streams);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
//result.Content.Headers.ContentLength = data.Length;
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = "test.zip";
return this.Ok(result);
}
The issue I am facing is that after the zip file downloaded at client end when modified as a test.bin has its stream contents (byte[] data in this example’s contents) missing. (I am getting back a test.zip file. When I change the file locally from test.zip to test.bin, I am seeing that the File’s contents as shown below. It does not contain the Response.Content values. P.S. I have also tried the MIME type “application/octet-stream” as well. No luck!)
Test.zip aka test.bin’s contents:
{"version":{"major":1,"minor":1,"build":-1,"revision":-1,"majorRevision":-1,"minorRevision":-1},
"content":{"headers":[{"key":"Content-Type","value":["application/zip"]},
{"key":"Content-Disposition","value":["attachment; filename=test.zip"]}]},
"statusCode":200,"reasonPhrase":"OK","headers":[],"isSuccessStatusCode":true}
Can someone please help me on how we can set result.Content with a MemoryStream object (I have seen example of “FileStream” at other places on google to set “result.Content” but I want to use MemoryStream object only!). I am highlighting this because I think the problem lies with setting the MemoryStream object to the result.Content (in order to properly save the streams content into the result.Content object)
P.S. I have also gone thru Uploading/Downloading Byte Arrays with AngularJS and ASP.NET Web API (and a bunch of other links) but it did not help me much… :(
Any help is greatly appreciated. Thanks a lot in advance :)
I got my issue solved!!
All I did was to change the Response Type to HttpResponseMessage and use "return result" in the last line rather than Ok(result) { i.e. HttpResponseMessage Type rather than OKNegiotatedContentResult Type)
Consider the following code:
QTextDocument * doc = ui->textBrowser->document();
doc->addResource(QTextDocument::ImageResource, QUrl("img://smiley"), QImage("happy.png"));
QTextCursor cursor = ui->textBrowser->textCursor();
cursor.insertHtml("Sample text ");
cursor.insertImage("img://smiley");
ui->textBrowser->setTextCursor(cursor);
(ui->textBrowser is a pointer to a QTextBrowser object)
When I copy the image to the clipboard, it is represented by an object replacement character (U+FFFC). Is it possible to change this behavior and save e.g. ":-)" instead?
Note that I am using Qt 5.2, so it's fine to use any functions introduced in Qt 5.
I'm afraid there is no simple way. In a web browser alt attribute would help, but Qt doesn't support it.
You can track clipboard's changes and correct its content.
Initialization:
QClipboard* clipboard = QApplication::clipboard();
connect(clipboard, SIGNAL(changed(QClipboard::Mode)),
this, SLOT(clipboard_changed()));
Clipboard correction (example):
void MainWindow::clipboard_changed() {
QClipboard* clipboard = QApplication::clipboard();
const QMimeData* data = clipboard->mimeData();
QString html = data->html();
if (html.contains("<img src=\"img://smiley\" />")) {
QString new_html = html;
new_html.replace("<img src=\"img://smiley\" />", ":-)");
QTextDocument doc;
doc.setHtml(new_html);
QString text = doc.toPlainText();
if (text != data->text()) {
QMimeData* new_data = new QMimeData();
new_data->setHtml(html);
new_data->setText(doc.toPlainText());
clipboard->setMimeData(new_data);
}
}
}
Of course you will need more sophisticated implementation for a real program.
I use QTextDocument just to convert HTML to plain text.
Ok so, basically my problem is with reading and XML file from IsolatedFileStorage. I'll go through the process that leads to my error and then I'll list the relevant code and XML file.
On the first execution it recognises that the file does not exist - it therefore creates the file in IsolatedFileStorage
On the second execution it can now see that the file does exist and so it loads the XML file
On the third execution it can see that it exists - but it throws an XML error
I cannot for the life of me find a solution to it (link to other discussion on MSDN here)
So the code for reading/creating the XML file in IsolatedFileStorage is as follows:
try
{
/***********************
* CHECK THE SETTINGS
********************/
if (store.FileExists("AppSettings.xml"))
{
streamSettings = new IsolatedStorageFileStream("AppSettings.xml", System.IO.FileMode.Open, store);
DebugHelp.Text = "AppSettings.xml exists... Loading!";
streamSettings.Seek(0, System.IO.SeekOrigin.Begin);
xmlDoc = XDocument.Load(streamSettings, LoadOptions.None);
}
else
{
streamSettings = new IsolatedStorageFileStream("AppSettings.xml", System.IO.FileMode.Create, store);
DebugHelp.Text = "AppSettings.xml does not exist... Creating!";
xmlDoc = XDocument.Load("AppSettings.xml", LoadOptions.None);
}
if (xmlDoc != null)
xmlDoc.Save(streamSettings);
}
catch (Exception e)
{
DebugHelp.Text = e.ToString();
}
finally
{
streamSettings.Close();
}
And the related XML file is as follows:
<?xml version="1.0" encoding="utf-8" ?>
<Settings>
</Settings>
Extremely advanced I know - however it throws the following error (here) and you can find the full error text at the bottom of the Social.MSDN page.
Please help - I have been looking for a solution (as the one on the social.msdn site didn't work) for about 2 weeks now.
Why don't you try to read file using a simple StreamReader ? Below a part of a method I have created to readfile from store. Have a try, check your content, and then try loading xml from String (XDocument.Parse etc ...)
String fileContent = String.Empty;
using (_store = IsolatedStorageFile.GetUserStoreForApplication())
{
if (_store.FileExists(file))
{
_storeStream = new IsolatedStorageFileStream(file, FileMode.Open, _store);
using (StreamReader sr = new StreamReader(_storeStream))
{
fileContent = sr.ReadToEnd();
}
__storeStream.Close();
return fileContent;
}
else {
return null;
}
}
It looks to me like the problem is in your save method - it looks like you are maybe appending the settings each time you close - to overwrite your existing settings, you need to ensure that you delete your existing file and create a new one.
To help debug this, try using http://wp7explorer.codeplex.com/ - this might help you see the raw file "on disk"
As an aside, for settings in general, do check out the AppSettings that IsolatedStorage provides by default - unless you have complicated needs, then these may suffice on their own.
Your code sample isn't complete so it's hard to say for sure but, rather than just seeking to the start of the file you may find it easier to just delete it if it already exists. You can do this with FileMode.Create. In turn this means you can do away with the need to check for the existing file.
I suspect that the problem is that you are writing a smaller amount of text to the file on subsequent attempts and so leaving part of the original/previous text behind. In turn this creates a file which contains invalid XML.
I have an existing PDF and I can use FdFWriter to input to text boxes. It works well. Now I have an image. I have read the documentation and looked at many examples but they all create new documents and insert an image. I want to take an existing PDF and insert an image into either an image field or as the icon image of a button. I have tried but it corrupts the document.
I need to be able to take an existing document and put an image on it. I do not want to open, read, replace, and delete the original. This original changes and the name "original" only means the source file in this context. There are many PDF files like this that need an image.
Thank you for any help.
Edit - I am very thankful for the code below. It works great, but the problem for me is that the existing PDF has digital signatures on it. When the document is copied like this (into result.pdf) those signatures, while still present, have a different byte count or other item that is corrupted. This means the signatures, while they show up on result.pdf, have an icon next to them that state "invalid signature."
In case it matters I am using a Topaz signature pad to create my signatures, which has it's own security. Merely copying the PDF will not corrupt it but the process below will.
I am trying to put the image on the existing document, not a copy of it, which in this case matters.
Also, by signature, I mean handwritten, not pin numbers.
Thank you again.
EDIT - Can PdfSignatureAppearance be used for this?
EDIT - I seem to be able to do it with:
var stamper = new PdfStamper(reader, outputPdfStream,'1',true);
If you want to change the contents of an existing PDF file and add extra content such as watermarks, pagenumbers, extra headers, PdfStamper is the object you need. I have successfully used the following code to insert an image into an existing pdf file to a given absolute position:
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
class Program
{
static void Main(string[] args)
{
using (Stream inputPdfStream = new FileStream("input.pdf", FileMode.Open, FileAccess.Read, FileShare.Read))
using (Stream inputImageStream = new FileStream("some_image.jpg", FileMode.Open, FileAccess.Read, FileShare.Read))
using (Stream outputPdfStream = new FileStream("result.pdf", FileMode.Create, FileAccess.Write, FileShare.None))
{
var reader = new PdfReader(inputPdfStream);
var stamper = new PdfStamper(reader, outputPdfStream);
var pdfContentByte = stamper.GetOverContent(1);
Image image = Image.GetInstance(inputImageStream);
image.SetAbsolutePosition(100, 100);
pdfContentByte.AddImage(image);
stamper.Close();
}
}
}
When you insert the image you have the possibility to resize it. You can take a look at transformation matrix in the iTextSharp documentation.
Here is a similar example whichi inserts an image on the page using the stamper:
Gmane iTex Mailing List Post
I could solve my problem by simply adding following lines to my signing code to add image
var image = iTextSharp.text.Image.GetInstance(#"C:\Users\sushil\Documents\sansign.jpg");
appearance.Acro6Layers = true;
appearance.SignatureGraphic = image;
appearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION;
As I was signing document with visible digital signature , now I can have both image and digital signature properties side by side
in the .net core6 that uses DDD try this declare class in Infrastructure Layer
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
public async Task<string> SignatureToPdf(string pathPdfFile, string
pathSignatureImage, string pathOutputName)
{
var webRootPath = hostingEnvironment.ContentRootPath;
if (!File.Exists(Path.Combine(webRootPath, pathPdfFile))) return
null;
await using Stream inputPdfStream =
new FileStream(Path.Combine(webRootPath, pathPdfFile),
FileMode.Open, FileAccess.Read, FileShare.Read);
await using Stream inputImageStream =
new FileStream(Path.Combine(webRootPath, pathSignatureImage), FileMode.Open, FileAccess.Read, FileShare.Read);
await using Stream outputPdfStream =
new FileStream(Path.Combine(webRootPath, pathOutputName),
FileMode.Create, FileAccess.Write, FileShare.None);
var reader = new PdfReader(inputPdfStream);
var stamper = new PdfStamper(reader, outputPdfStream);
var pdfContentByte = stamper.GetOverContent(1);
var image = Image.GetInstance(inputImageStream);
image.SetAbsolutePosition(100, 100);
pdfContentByte.AddImage(image);
stamper.Close();
return "ok";
}
pdftk can do this. It's not a library but you can easily call it from your code as a .exe.
See stamp and background commands:
http://www.pdflabs.com/docs/pdftk-man-page/
ref: How to do mail merge on top of a PDF?