C++ How to use Range parameter with InlineShapes AddPicture() method - c++

There is very limited documentation on using this method with C++. Most of the documentation is for VB. Please help me to 1) create a range object 2) use this range object with the AddPicture() method.
Here is the AddPicture definition for C++:
LPDISPATCH InlineShapes::AddPicture(LPCTSTR FileName, VARIANT* LinkToFile, VARIANT* SaveWithDocument, VARIANT* Range)
Below is working code that inserts an image into a word document. It inserts at top of doc because the range parameter(4th parameter, currently 'covOptional') is not specified. There is other code that sets up m_disp to interact with document of interest.
_Document objDoc;
COleVariant covOptional;
//instantiate the document object
objDoc.AttachDispatch(m_disp);
//adding image to doc
InlineShapes objInlineShapes(objDoc.GetInlineShapes())
objInlineShapes.AddPicture("C:\\QR.png", covOptional, covOptional, covOptional);
Here is more info on what I am trying to do incase there are alternative ways. I have a word document that I need to add a png image to. I see a couple ways of doing this: 1) hardcode range objects that specify the position in the document of the png to be inserted into 2) add anchor strings (ex. %pngLocation%) to the document. Find a way to return a range that represents this string's location. Use that range with the AddPicture() method.

I had to use a different msword library, but I got this to work with the following code.
#import "C:\Program Files (x86)\Microsoft Office\root\Office16\MSWORD.OLB" named_guids raw_native_types rename("ExitWindows", "WordExitWindows") rename("FindText", "WordFindText"), rename("VBE", "testVBE")
#include "path\debug\msword.tlh"
//setting up
Word::WindowPtr pWindow = w_app.GetActiveWindow();
Word::Range* pRange = pWindow->Selection->GetRange();
pRange->Start = 20;
pRange->End = 20;
VARIANT vTargetRange;
vTargetRange.vt = VT_DISPATCH;
vTargetRange.pdispVal = pRange;
I was able to use '&vTargetRange' as the range parameter in AddPicture().
Thank you to Castorix31.

Related

Need to create a .doc file with list of items using Aspose

I have been working on legacy application where i am using Aspose.Words.jdk15.jar to print the .doc file. I have a requirement where i am getting list of value then we have to loop & print it in the doc file.
And that value we are replacing in doc using range.replace() method . This doc already exists in my workspace where we have mapped the value like this
Component Name:$COMPONENT_NAME
Billing Effective Date:$EFFECTIVE_DATE
Billing End Date:$END_DATE
and the code which i have written to replace the value of doc. So, my requirement is I need this value multiple times in my doc as per size of list.
for(int i=0;i<details.size();i++)
{
doc.getRange().replace("$COMPONENT_NAME" , checkNull(details.get(i).getComponentName()) + “,”, false, false);
doc.getRange().replace("$EFFECTIVE_DATE" , checkNull(details.get(i).getBillEffectiveDate()) + “,”, false, false);
doc.getRange().replace("$END_DATE" , checkNull(details.get(i).getBillEndDate()) + “,”, false, false);
}
The best way to achieve what you need is using mail Merge feature.
https://docs.aspose.com/words/java/about-mail-merge/
But in this case you need to replace your placeholders with mergefields in your template.
If you cannot change the template, you can clone the the document for each item in your list, replace values in the cloned document and them merge documents together to get the final result. Code will look like the following:
// Open template
Document doc = new Document("C:\\Temp\\in.doc");
// Create document where result will be stored to.
// Simply clone the original template without children,
// In this case styles of the original document will be kept.
Document result = (Document)doc.deepClone(false);
for(int i=0; i<details.length; i++)
{
Document component = doc.deepClone();
component.getRange().replace("$COMPONENT_NAME", details[i].getComponentName());
component.getRange().replace("$EFFECTIVE_DATE", details[i].getBillEffectiveDate().toString());
component.getRange().replace("$END_DATE", details[i].getBillEndDate().toString());
// Append the result to the final document.
result.appendDocument(component, ImportFormatMode.USE_DESTINATION_STYLES);
}
result.save("C:\\Temp\\out.doc");
But I would preferer Mail Merge approach.

Removing invalid URLs from MSHTML document before it is loaded

I use MSHTML (IHTMLDocument) to display offline HTML which may contain various links. These are loaded from email HTML.
Some of them have URLs starting with // or / for example:
<img src="//www.example.com/image.jpg">
<img src="/www.example.com/image.jpg">
This takes a lot of time to resolve and show the document because it cannot find the URL obviously as it doesn't start with http:// or https://
I tried injecting <base> tag into <head> and adding a local known folder (which is empty) and that stopped this problem. For example:
<base href="C:\myemptypath\">
However, if links begin with \\ (UNC path) the same problem and long loading time begin again. Like:
<img src="\\www.something.com\image.jpg">
I also tried placing WebBrowser control into "offline" mode and all other tricks I could think of and couldn't come up with anything short of RegEx and replacing all the links in the HTML which would be terribly slow solution (or parsing HTML myself which defeats the purpose of MSHTML).
Is there a way to:
Detect these invalid URLs before the document is loaded? - Note: I already did navigate through DOM e.g. WebBrowser1.Document.body.all collection, to get all possible links from all tags and modify them and that works, but it only happens after the document is already loaded so the long waiting time before loading gives up is still happening
Maybe trigger some event to avoid loading these invalid links and simply replace them with about:blank or empty "" text like some sort of "OnURLPreview" event which I could inspect and reject loading of URLs that are invalid? There is only OnDownloadBegin event which is not it.
Any examples in any language are welcome although I use Delphi and C++ (C++ Builder) as I only need the principle here in what direction to look at.
After a long time this is the solution I used:
Created an instance of CLSID_HTMLDocument to parse HTML:
DelphiInterface<IHTMLDocument2> diDoc;
OleCheck(CoCreateInstance(CLSID_HTMLDocument, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&diDoc)));
Write IHTMLDocument2 to diDoc using Document->write
// Creates a new one-dimensional array
WideString HTML = "Example HTML here...";
SAFEARRAY *psaStrings = SafeArrayCreateVector(VT_VARIANT,0,1);
if (psaStrings)
{
VARIANT *param;
BSTR bstr = SysAllocString(HTML.c_bstr());
SafeArrayAccessData(psaStrings, (LPVOID*)&param);
param->vt = VT_BSTR;
param->bstrVal = bstr;
SafeArrayUnaccessData(psaStrings);
diDoc->write(psaStrings);
diDoc->close();
// SafeArrayDestroy calls SysFreeString for each BSTR
//SysFreeString(bstr); // SafeArrayDestroy should be enough
SafeArrayDestroy(psaStrings);
return S_OK;
}
Parse unwanted links in diDoc
DelphiInterface<IHTMLElementCollection> diCol;
if (SUCCEEDED(diDoc->get_all(&diCol)) && diCol)
{
// Parse IHTMLElementCollection here...
}
Extract parsed HTML into WideString and write into TWebBrowser
DelphiInterface<IHTMLElement> diBODY;
OleCheck(diDoc->get_body(&diBODY));
if (diBODY)
{
DelphiInterface<IHTMLElement> diHTML;
OleCheck(diBODY->get_parentElement(&diHTML));
if (diHTML)
{
WideString wsHTML;
OleCheck(diHTML->get_outerHTML(&wsHTML));
// And finally use the `Document->write` like above to write into your final TWebBrowser document here...
}
}

How to get placeholder size in TensorFlow C++ API?

I want to use C++ to load TensorFlow model. And I want to know size of model's input, which is the placeholder in the model.
I google this problem, but I just find this link in stackoverflow :
C++ equivalent of python: tf.Graph.get_tensor_by_name() in Tensorflow?
Although I can get node, but tensorflow document don't tell me how to access the size of the node. So is there anyone know something about this?
Thank you so much!
OK,after many times attempts. I have find a workaround solution, It maybe tricky but works well.
At first, we can get the placeholder node using following code:
GraphDef mygd = graph_def.graph_def();
for (int i = 0; i < mygd.node_size(); i++)
{
if (mygd.node(i).name() == input_name)
{
auto node = mygd.node(i);
}
}
Then through the NodeDef.pd.h(tensorflow/core/framework/node_def.pb.h), we can get AttrValue through code like below:
auto attr = node.attr();
Then through the attr_value.cc(tensorflow/core/framework/attr_value.cc), we can get the shape attr value through code like below:
tensorflow::AttrValue shape = attr["shape"];
and the shape AttrValue is the structure used to store shape information. We can get the detail information through the function SummarizeAttrValue in tensorflow/core/framework/attr_value_util.h
string size_summary = SummarizeAttrValue(shape);
And then we can get the string format of shape like below:
[?,1024]

Aspose.PDF How Replace replace text on PDF page to all upper case

I am trying to replace text on a specific page to upper case using Aspose.PDF for .Net. If anyone can provide any help that would be great. Thank you.
My name is Tilal Ahmad and I am a developer evangelist at Aspose.
You may use the documentation link for searching and replacing text on a specific page of the PDF document. You should call the Accept method for specific page index as suggested at the bottom of the documentation. Furthermore, for replacing text with uppercase you can use ToUpper() method of String object as follows.
....
textFragment.Text = textFragment.Text.ToUpper();
....
Edit: A sample code to change text case on a specific PDF page
//open document
Document pdfDocument = new Document(myDir + "testAspose.pdf");
//create TextAbsorber object to find all instances of the input search phrase
TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber("");
//accept the absorber for all the pages
pdfDocument.Pages[2].Accept(textFragmentAbsorber);
//get the extracted text fragments
TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments;
//loop through the fragments
foreach (TextFragment textFragment in textFragmentCollection)
{
//update text and other properties
textFragment.Text = textFragment.Text.ToUpper();
}
pdfDocument.Save(myDir+"replacetext_output.pdf");

Word automation with C++ Builder 5

I'm trying to control Word through a c++ builder 5 application. I would like to
open a ".dot" model file created with Word and modify it. In the ".dot" model file
there are some fields. For example, Title, LastName, FirstName, Address
and so on, and I would like to modify these fields putting text into them and then
saving file with a new name, for example "Warning.doc" leaving the ".dot" file
unaltered.
I can open the file, count the number of fields it contains, but then
when it comes to replacing each field with a string I don't know how to do because
I don't have a complete documentation on OleFunction and OlePropertyGet methods. I attach my source code to this message, can anybody help me to solve this problem please?
try
{
my_word = Variant::CreateObject("word.application");
}
catch (...)
{
Application->MessageBox("Unable to obtain Word automation object",
"Error:",MB_OK | MB_ICONERROR);
}
my_word.OlePropertySet("Visible", (Variant)true);
void __fastcall TForm1::Button2Click(TObject *Sender)
{
Variant this_doc;
Variant my_fields;
Variant test;
int k,field_count;
AnsiString test1;
AnsiString filename = "d:\\ProgrammaWord\\1-Avviso.dot";
my_docs = my_word.OlePropertyGet("Documents");
this_doc = my_docs.OleFunction("Open", filename);
my_fields = this_doc.OlePropertyGet("Fields");
field_count = my_fields.OlePropertyGet("Count");
for(k = 1; k <= field_count; k++)
{
test = my_fields.OleFunction("Item",(Variant)k);
test1 = test.OleFunction("Value"); //This instruction throws an exception
// "Value" is not a recognized parameter
// in this case
Memo1->Lines->Add(test1);
}
}
I never used word Ole but I used it for Outlook and Excel, I can't try it with word since I'm currently on OSX but you should try something similar as what I did.
The generic way of using Ole was to OleGetproperty() while you get the targeted field then OleSetProperty("action", ...).
for example when I wanted to change the color of the text in a particular cell of my excel document I used:
Variant _excel = Variant::CreateObject("Excel.Application");
Variant _workbook = _excel.OlePropertyGet("WorkBooks").OleFunction("Open", filename);
Variant _worksheet = _workbook.OlePropertyGet("WorkSheets", sheet);
_worksheet.OlePropertyGet("Cells", row, col).OlePropertyGet("Font").OlePropertySet("Color", color);
Here I instanciate an excel object, then I load a file into it (_workbook), then I select the _worksheet from the _workbook and I start my business.
Here comes the interesting part:
It concist of getting to a particular cell, getting the font object from it, and then setting the color of this font object.
Disclaimer: This is an example from my sources for excel, it's not directly related to your example, but maybe you can understand the principe with it. I can't try to figure out what you need because I have no windows right now.
Hope this can help you. Finding ressources for OLE can be fierce if you don't have the good patterns to look for.