Adding symbols to word document using docx4j - symbols

I am trying to add a Wingdings symbol using the following code to the docx.
P symp = factory.createP();
R symr = factory.createR();
Sym sym = factory.createRSym();
sym.setFont("Wingdings");
sym.setChar("FOFC");
symr.getContent().add(sym);
symp.getContent().add(symr);
mainPart.getContent().add(symp);
I get invalid content errors on opening the document. When I tried to add the symbols directly to a word docx, unzipped the docx and looked at the document.xml, I see the paragraph has rsidR and rsidDefault attributes. When I read about these attributes from this link, How to generate RSID attributes correctly in Word .docx files using Apache POI?, I see that they are random and only necessary to track changes in the document. So then, why does Microsoft word keeps expecting it and gives me the errors?
Any ideas/suggestions?

I wonder whether Sym support is in docx4j in the way you expect.
I tried your code and got the same issue, but I must confess to not having investigated symbols before. As an experiment, I added a symbol using the relevant “Insert” menu command in Word 2010, and then checked the resulting OpenXML—it’s really quite different to the mark-up expected when inserting an Sym element.
Rather than manipulating symbols, have you tried inserting the text directly instead? For example, this will insert a tick character (not sure if that’s what you’re after):
P p = factory.createP();
R r = factory.createR();
RPr rpr = factory.createRPr();
Text text = factory.createText();
RFonts rfonts = factory.createRFonts();
rfonts.setAscii("Wingdings");
rfonts.setCs("Wingdings");
rfonts.setHAnsi("Wingdings");
rpr.setRFonts(rfonts);
r.setRPr(rpr);
text.setValue("\uF0FC");
r.getContent().add(text);
p.getContent().add(r);
mainPart.getContent().add(p);

Related

R/exams unicode char in *.Rnw question files are not propoerly displayed: é displayed as <U+00E9> in final PDF

I am struggling to produce an exam sheet in French using exams2nops. There are accents in the text provided in the intro and title argument of this function and also in the Rnw files containing the function. The formers are correctly displayed in the resulting PDF, but not the later, for example é from a Rnw file is displayed as <U+00E9>.
The call to exams2nops looks like this:
exams2nops(file=myexam, n = N.students, dir = '.',
name = paste0('exam-', exam.date),
title = "Examen écrit",
course = course.id,
institution = "",
logo = paste(exams.dir, 'input/logo.jpg', sep='/'),
date = exam.date,
replacement = TRUE,
intro = intro,
blank=round(length(myexam)/4),
duplex = TRUE, pages = NULL,
usepackage = NULL,
language = "fr",
encoding = "UTF-8",
startid = 1,
points = c(1), showpoints = TRUE,
samepage = TRUE,
twocolumn = FALSE,
reglength = 9,
header=NULL)
Note that "Examen écrit" is correctly displayed in the final PDF, the problem is with the accent in the Rnw files. The function call yields no error.
The *.tex files by generated by exams2nops, already have the problem. For example, the sentense 'Quarante patients ont été inscrits' in the original Rnw file, becomes 'Quarante patients ont <U+00E9>t<U+00E9> inscrits' in the tex file.
I use exams_2.4-0 with R 4.2.2 with TeXShop 4.70 on OSX 11.6.
I checked that Rnw are utf-8 encoded, for example:
$ file -I question1.Rnw
question1.Rnw: text/x-tex; charset=utf-8
It seems they are utf-8-encoded, indeed. These files were translated with deepl or google translate, then edited in emacs.
I tried setting the encoding parameter of exams2nops to latin-1. It did not help.
Any Idea?
The problem disapeared after setting R 'locales' properly. A recurrent problem with OSX R installs. The symptome is:
During startup - Warning messages:
1: Setting LC_CTYPE failed, using "C"
2: Setting LC_COLLATE failed, using "C"
3: Setting LC_TIME failed, using "C"
4: Setting LC_MESSAGES failed, using "C"
5: Setting LC_MONETARY failed, using "C"
at start up. This thread explains how to fix it: Installing R on Mac - Warning messages: Setting LC_CTYPE failed, using "C".
I'm collecting a few further comments here in addition to the existing answer:
The only encoding (beyond ASCII) supported by R/exams, starting from version 2.4-0, is UTF-8. Support for other encodings like latin1 etc. has been discontinued.
As only UTF-8 is supported the encoding does not have to be specified in R/exams function calls anymore (as still might be advised in older tutorials).
To leverage this support of UTF-8, R has to be configured with a suitable locale. A "C" locate (see the answer by #vdet) is not sufficient.
When using R/LaTeX (Rnw) exercises all issues with encodings can also be avoided entirely by using LaTeX commands for special characters, e.g., {\'e}t{\'e} instead of été. The latter is of course more convenient but the former can be more robust, especially when working with teams of instructors living on different operating systems with different locale settings.
When using LaTeX commands instead of special characters in R strings (as opposed to the exercise files), then remember that the backslash has to be escaped. For example, the argument title = "Examen écrit" becomes title = "Examen {\\'e}crit".

BibTeX: I didn't find a database entry for "" -- empty database entry?

I am working on a Latex template and I keep getting the following error:
BibTeX: I didn't find a database entry for ""
At first I though something in my bib had an unexpected empty citation, but there is none. I've also tried to rename the bib file, no luck... any ideas?
I've look everywhere and I can't find a solution yet. Any help is appreciated.
It could be possible there's a non-display character (like a zero width space, for example) that got into one of your citations.
Try doing a find command for "cite{" and compare it with the number of results for "cite". If there's a difference then you've found the citation with a stray character in it, and you can just copy a properly formatted string and paste in place.
There could also be such a character within after the bracket which will cause the same problem, but that will be a bit harder to find.
I thought of this thanks to this question where the author also had a problem with a non-displaying character getting into his citation. https://tex.stackexchange.com/questions/33416/bibtex-i-didnt-find-a-database-entry-for
Try searching any .tex files in your project for an empty citation, in my case I found a \cite{} causing the issue
This may be caused by duplication of database files in the command \bibliography{}.
The bibtex command will produce the following output
This database file appears more than once: foo.bib
---line 4 of file Untitled2.aux
: \bibdata{foo,foo
: }
I'm skipping whatever remains of this command
Database file #1: foo.bib
(There was 1 error message)
if you write in your tex file as
\bibliography{foo2022, foo2022}
Such an error won't cause any trouble if the duplication appears as the last database file. Unfortunately, if you append another database file after that duplicated one, as suggested by the error message, the new file is ignored so bibtex can't find that database entry.
So review the error message from bibtex and exclude the duplicated database files.
I have prepared some tex and bib files for you to reproduce such an error.
tex file
\documentclass[a4paper,12pt,oneside]{report}
\usepackage[round]{natbib}
\bibliographystyle{plainnat}
\usepackage[textheight=23.7cm,
hmargin=26mm,
top=26mm,
headheight=0.5cm,
headsep=0.5cm,
]{geometry}
\renewcommand{\bibname}{References}
\begin{document}
\citep{foo2022}, \citep{foo2:foo2022}
\bibliography{foo,foo,foo2}
\end{document}
foo.bib
#article{foo2022,
author = {Hello, World},
journal = {Journal},
month = {01},
number = {1},
pages = {1-10},
title = {Title},
volume = {100},
year = {2022}}
foo2.bib
#article{foo2:foo2022,
author = {Hello, World},
journal = {Journal},
month = {01},
number = {1},
pages = {1-10},
title = {Title},
volume = {100},
year = {2022}}
To compile, use the following commands
pdflatex <your file>
bibtex <your file>
pdflatex <your file>
pdflatex <your file>
To correct the above-mentioned error, change
\bibliography{foo,foo,foo2}
to
\bibliography{foo,foo2}

Aspose generated doc file turns underscores into white space for some users

I am updating archaic code that creates memos. The code was written to use bookmarks inside of manually created template.doc files that aspose can write to. The problem comes from this chunk of code.
foreach (Addressee infoAddressee in ConfigManager.GetConfig().Addressees)
{
if (infoAddressee.Abbreviation == Memo.AddresseeAbbr.ToUpper() &&
infoAddressee.NeedsThisLine)
{
WriteMeString = "FOO BARR ________";
break;
}
}
if (WriteMeString != "")
{
builder.MoveToBookmark("BOOKMARK");
builder.Write(WriteMeString);
}
}
This works for me, but the two people who have tested this chunk of code have the "FOO BARR _______" line appear as "FOO BARR "
the seven underlines are replaced with spaces(the spacing exists on the word doc, but Stack overflow concatenates consecutive spaces). I am not sure what could cause this.
To test we need to copy the file from the remote dev environment into our local environment, I believe this to be the source of the issue, but i do not know for sure.
What I have already tried:
The testers and me are supplying the exact same input for the document.
The testers and I had a slightly different way to save the document and copy paste it over to the local environment, but doing it my way did not change anything.
I am unsure of what could do this for some users but not for others, any suggestions for things i could check out, be it literature with information on the subject or proposed solutions, would be greatly appreciated
I checked the scenario on my side and cannot reproduce the problem. Underscores are properly displayed in the output document. Here are few things to try.
Try setting bookmark text instead of moving to it and writing text.
doc.Range.Bookmarks["BOOKMARK"].Text = WriteMeString;
Try checking whether string is written correctly into the document.
builder.MoveToBookmark("BOOKMARK");
builder.Write("FOO BARR ________");
Assert.AreEqual("FOO BARR ________", builder.Document.Range.Bookmarks["BOOKMARK"].Text);
using (MemoryStream ms = new MemoryStream())
{
builder.Document.Save(ms, SaveFormat.Doc);
ms.Position = 0;
Document tempDoc = new Document(ms);
Assert.AreEqual("FOO BARR ________", tempDoc.Range.Bookmarks["BOOKMARK"].Text);
}
Compare the documents produced on your side and on the testers side yourself (I suppose, you have already done this, but just in case). Probably the documents are correct, but there is difference in viewer used on your and testers side.
Disclosure: I work at Aspose.Words team.

F# FSI - Is there a limit to the script length? String Literal appears too long

On transferring a F# file -- Jira.fs to a script file -- Jira.fsx
I am encountering a problem with a constant string that uses triple quotes and within it contains double quotes (example below)
Jira.fs = success
Jira.fsx = fails with error FS0010: Unexpected symbol ':' in expression. Expected '}' or other token.
Warnings include - Warning: line too long, ignoring some characters
Is there a limit to .fsx scripts?
If so is there a recommended way around this? Just read in the string from a file?
Code below: thanks
[<Literal>]
let childIssueSchema = """ {"expand":"renderedFields,names,schema,transitions,operations,editmeta,changelog","id":"18043","self":"https://atlassian.au.MyCompany.net/jira/rest/api/latest/issue/18043","key":"DPMITPRODU-141","fields":{"progress":{"progress":0,"total":0},"summary":"APC - Calculator link on AOL ","customfield_10560":{"self":"https://atlassian.au.MyCompany.net/jira/rest/api/2/customFieldOption/10340","value":"Yes","id":"10340"},"customfield_11067":null,"timetracking":{},"customfield_11066":null,"issuetype":{"self":"https://atlassian.au.MyCompany.net/jira/rest/api/2/issuetype/6","id":"6","description":"A user story","iconUrl":"https://atlassian.au.MyCompany.net/jira/images/icons/sales.gif","name":"User Story","subtask":false},"customfield_10562":null,"customfield_11069":null,"customfield_11068":null,"customfield_11160":"4837","customfield_11161":null,"customfield_11660":null,"timespent":null,"reporter":{"self":"https://atlassian.au.MyCompany.net/jira/rest/api/2/user?username=lkaligotla","name":"lkaligotla","emailAddress":"lkaligotla#MyCompany.com.au","avatarUrls":{"16x16":"https://atlassian.au.MyCompany.net/jira/secure/useravatar?size=small&avatarId=10102","48x48":"https://atlassian.au.MyCompany.net/jira/secure/useravatar?avatarId=10102"},"displayName":"Lakshmi Kaligotla","active":true},"created":"2013-12-31T14:39:09.457+1100","updated":"2014-01-02T09:32:57.023+1100","customfield_10041":null,"priority":{"self":"https://atlassian.au.MyCompany.net/jira/rest/api/2/priority/3","iconUrl":"https://atlassian.au.MyCompany.net/jira/images/icons/priority_major.gif","name":"Medium","id":"3"},"description":"The current Age pension Calculator Icon must lead to a landing page with content and Start Calculator Button \r\n\r\nOn Click of start Calculator button calculator Home Page with instructions and start calculator button ","customfield_10002":null,"customfield_10003":null,"customfield_10040":null,"issuelinks":[{"id":"13177","self":"https://atlassian.au.MyCompany.net/jira/rest/api/2/issueLink/13177","type":{"id":"10010","name":"CrossProjectLink","inward":"part of","outward":"contains","self":"https://atlassian.au.MyCompany.net/jira/rest/api/2/issueLinkType/10010"},"inwardIssue":{"id":"18036","key":"DPMITPROJ-35","self":"https://atlassian.au.MyCompany.net/jira/rest/api/2/issue/18036","fields":{"summary":"APC - Calculator","status":{"self":"https://atlassian.au.MyCompany.net/jira/rest/api/2/status/10003","description":"User has placed this item in the queue","iconUrl":"https://atlassian.au.MyCompany.net/jira/images/icons/status_visible.gif","name":"In Queue","id":"10003"},"priority":{"self":"https://atlassian.au.MyCompany.net/jira/rest/api/2/priority/3","iconUrl":"https://atlassian.au.MyCompany.net/jira/images/icons/priority_major.gif","name":"Medium","id":"3"},"issuetype":{"self":"https://atlassian.au.MyCompany.net/jira/rest/api/2/issuetype/5","id":"5","description":"A big user story that needs to be broken down.","iconUrl":"https://atlassian.au.MyCompany.net/jira/download/resources/com.pyxis.greenhopper.jira:greenhopper-webactions/images/ico_epic.png","name":"Epic","subtask":false}}}}],"customfield_10000":null,"customfield_10765":null,"subtasks":[],"customfield_10767":null,"status":{"self":"https://atlassian.au.MyCompany.net/jira/rest/api/2/status/10016","description":"","iconUrl":"https://atlassian.au.MyCompany.net/jira/images/icons/status_open.gif","name":"Backlog","id":"10016"},"labels":[],"workratio":-1,"project":{"self":"https://atlassian.au.MyCompany.net/jira/rest/api/2/project/DPMITPRODU","id":"11433","key":"DPMITPRODU","name":"DPMIT-Products","avatarUrls":{"16x16":"https://atlassian.au.MyCompany.net/jira/secure/projectavatar?size=small&pid=11433&avatarId=11680","48x48":"https://atlassian.au.MyCompany.net/jira/secure/projectavatar?pid=11433&avatarId=11680"}},"environment":null,"customfield_10053":{"self":"https://atlassian.au.MyCompany.net/jira/rest/api/2/customFieldOption/10030","value":"Yes","id":"10030"},"aggregateprogress":{"progress":0,"total":0},"customfield_10050":"A link is available and on click leads to Calculor Landing page\r\nhttps://adviseronlineportal.com.au/Agepensioncalculator","components":[],"comment":{"startAt":0,"maxResults":0,"total":0,"comments":[]},"timeoriginalestimate":null,"customfield_10461":null,"customfield_10460":null,"customfield_11963":[{"self":"https://atlassian.au.MyCompany.net/jira/rest/api/2/customFieldOption/11441","value":"False","id":"11441"}],"customfield_10360":null,"votes":{"self":"https://atlassian.au.MyCompany.net/jira/rest/api/2/issue/DPMITPRODU-141/votes","votes":0,"hasVoted":false},"customfield_10261":null,"customfield_10262":null,"customfield_10263":{"self":"https://atlassian.au.MyCompany.net/jira/rest/api/2/customFieldOption/10061","value":"Yes","id":"10061"},"fixVersions":[],"resolution":null,"resolutiondate":null,"aggregatetimeoriginalestimate":null,"customfield_10161":null,"customfield_10160":null,"duedate":null,"customfield_10020":null,"customfield_10060":"4793","watches":{"self":"https://atlassian.au.MyCompany.net/jira/rest/api/2/issue/DPMITPRODU-141/watchers","watchCount":1,"isWatching":false},"customfield_10162":null,"worklog":{"startAt":0,"maxResults":0,"total":0,"worklogs":[]},"assignee":null,"attachment":[],"aggregatetimeestimate":null,"versions":[],"timeestimate":null,"customfield_10030":null,"customfield_10031":null,"aggregatetimespent":null}} """
type ChildJsonSchema = FSharp.Data.JsonProvider< childIssueSchema >
I don't think there is a limit on the size of a script file (not sure what would happen around 2GB, but that does not sound like a realistic scenario), but for some reason (not sure why!) there is a limit on a single line length.
This is a bit unfortunate when you just want to copy & paste sample for a JSON type provider, but if you're using """ quotes, then you can just have a newline character in the string and it will still be treated as a single constant string:
[<Literal>]
let childIssueSchema = """{"foo":1,
"bar":42}"""
type ChildJsonSchema = FSharp.Data.JsonProvider<childIssueSchema>
That said, in case you have long and complex samples, it might be better to save them to files and just point the type provider to a file. Assuming you have childIssue.json in the same folder as the source file, you should be able to write:
type ChildJsonSchema = FSharp.Data.JsonProvider<"childIssue.json">

How to open Excel file written with incorrect character encoding in VBA

I read an Excel 2003 file with a text editor to see some markup language.
When I open the file in Excel it displays incorrect characters. On inspection of the file I see that the encoding is Windows 1252 or some such. If I manually replace this with UTF-8, my file opens fine. Ok, so far so good, I can correct the thing manually.
Now the trick is that this file is generated automatically, that I need to process it automatically (no human interaction) with limited tools on my desktop (no perl or other scripting language).
Is there any simple way to open this XL file in VBA with the correct encoding (and ignore the encoding specified in the file)?
Note, Workbook.ReloadAs does not function for me, it bails out on error (and requires manual action as the file is already open).
Or is the only way to correct the file to go through some hoops? Either: text in, check line for encoding string, replace if required, write each line to new file...; or export to csv, then import from csv again with specific encoding, save as xls?
Any hints appreciated.
EDIT:
ADODB did not work for me (XL says user defined type, not defined).
I solved my problem with a workaround:
name2 = Replace(name, ".xls", ".txt")
Set wb = Workbooks.Open(name, True, True) ' open read-only
Set ws = wb.Worksheets(1)
ws.SaveAs FileName:=name2, FileFormat:=xlCSV
wb.Close False ' close workbook without saving changes
Set wb = Nothing ' free memory
Workbooks.OpenText FileName:=name2, _
Origin:=65001, _
DataType:=xlDelimited, _
Comma:=True
Well I think you can do it from another workbook. Add a reference to AcitiveX Data Objects, then add this sub:
Sub Encode(ByVal sPath$, Optional SetChar$ = "UTF-8")
Dim stream As ADODB.stream
Set stream = New ADODB.stream
With stream
.Open
.LoadFromFile sPath ' Loads a File
.Charset = SetChar ' sets stream encoding (UTF-8)
.SaveToFile sPath, adSaveCreateOverWrite
.Close
End With
Set stream = Nothing
Workbooks.Open sPath
End Sub
Then call this sub with the path to file with the off encoding.

Resources