NPOI XWPF how can I place text on a single line that is both left & right justified? - npoi

I'm new to using NPOI XWPF and trying to create my first document, so far it's going well. The only issue I have left is trying to place text on the same line that is both left and right justified, I want it to look like:
Area: 1(Left Jstfd) Grade Level/Course: 10th Grade Reading (Right Jstfd)
Below is the code snippet I'm using, it's just pushing all the text together on the left side of the page...blah
XWPFParagraph p2 = doc.CreateParagraph();
p2.Alignment = ParagraphAlignment.LEFT;
XWPFRun r3 = p2.CreateRun();
r3.SetBold(true);
r3.FontFamily = "Times New Roman";
r3.FontSize = 12;
r3.SetText("Area: " + ah.schoolArea);
XWPFRun r4 = p2.CreateRun();
r4.SetBold(true);
r4.FontFamily = "Times New Roman";
r4.FontSize = 12;
r4.SetText("Grade Level/Course: " + ah.filterParm);

Before trying to accomplish a task in (N)POI, it's always good to realize how said task is accomplished in Microsoft Word itself. You can't simply split a paragraph half-way a line, what you do is
Add a tab stop at the end of the line
Set it to right-aligned.
Type text on the left, hit tab, type text on the right
Unfortunately, it doesn't seem XWPFParagraph exposes tabstop functionality at this point. However, XWPFParagraph is a wrapper around the CT_P class, which maps 1:1 onto the underlying Office XML format. Using reflection, we can access this private field and use it to directly add the tabstop.
Sample code:
var paragraph = document.CreateParagraph();
var memberInfo = typeof(XWPFParagraph).GetField("paragraph", BindingFlags.NonPublic | BindingFlags.Instance);
if (memberInfo == null)
{
throw new Exception("Could not retrieve CT_P from XWPFParagraph");
}
var internalParagraph = (CT_P) memberInfo.GetValue(paragraph);
CT_PPr pPr = internalParagraph.AddNewPPr();
CT_Tabs tabs = pPr.AddNewTabs();
CT_TabStop tab = tabs.AddNewTab();
tab.pos = "9000";
tab.val = ST_TabJc.right;
var run = paragraph.CreateRun();
run.SetText("Left aligned");
run.AddTab();
run = paragraph.CreateRun();
run.SetText("Right aligned");
Result:

Related

MigraDoc Formatting

I am completely new to PDF creation including MigraDoc. I have gotten this far, which is really close to what I want for now. My question is that the text string (myMessage) that I pass to the "bodyParagraph" is up to 100 lines long, which causes three pages to be created, which is good. However the first page's Top margin is slightly greater than the second and third pages. I have no idea of why...
Basically, I am trying to create every page the same. Same header, footer and the body to take the same space regardless of the number of lines in the "bodyParagraph" content. If I have taken the completely wrong approach I would be open to suggestions.
Also, if there is a good tutorial to point me to that would be great. I can't really find anything but samples. I have learned everything from the samples, but sections, paragraph, etc is all new to me and I would like to get a better understanding of what I've done.
public static Document CreateWorkOrderPDF2(Document document, string filename, string WorkOrderHeader, string myMessage)
{
Section section = document.AddSection();
section.PageSetup.PageFormat = PageFormat.Letter;
section.PageSetup.StartingNumber = 1;
section.PageSetup.LeftMargin = 40;
//Sets the height of the top margin
section.PageSetup.TopMargin = 100;
section.PageSetup.RightMargin = 40;
section.PageSetup.BottomMargin = 40;
//MARGIN
HeaderFooter header = section.Headers.Primary;
header.Format.Font.Size = 16;
header.Format.Font.Color = Colors.DarkBlue;
MigraDoc.DocumentObjectModel.Shapes.Image headerImage = header.AddImage("../../Fonts/castorgate.regular.png");
headerImage.Width = "2cm";
Paragraph headerParagraph = section.AddParagraph();
headerParagraph = header.AddParagraph(WorkOrderHeader);
//BODY PARAGRAPH
Paragraph bodyParagraph = section.AddParagraph();
bodyParagraph = section.AddParagraph(myMessage);
bodyParagraph.Format.Font.Size = 10;
bodyParagraph.Format.Font.Color = Colors.DarkRed;
//paragraph.Format.Distancne = "3cm";
Paragraph renderDate = section.AddParagraph();
renderDate = section.AddParagraph("Work Order Generated: ");
renderDate.AddDateField();
return document;
}
The line Paragraph bodyParagraph = section.AddParagraph(); adds an empty paragraph. I assume that is the extra space on the first page.
Same issue with renderDate in the following code block.
Just remove the calls section.AddParagraph() to remove the empty paragraphs if you don't want them.
MigraDoc is much like Word and understanding sections, paragraphs, &c. in Word will also help you with MigraDoc. That knowledge along with the samples and IntelliSense should get you going.
You can use MigraDoc to create an RTF file, open the RTF in Word, and click the pilcrow to show formatting characters in Word.

kendo ui editor how to modify user selection with range object

Kendo UI 2015.2.805 Kendo UI Editor for Jacascript
I want to extend the kendo ui editor by adding a custom tool that will convert a user selected block that spans two or more paragraphs into block of single spaced text. This can be done by locating all interior p tags and converting them into br tags, taking care not to change the first or last tag.
My problem is working with the range object.
Getting the range is easy:
var range = editor.getRange();
The range object has a start and end container, and a start and end offset (within that container). I can access the text (without markup)
console.log(range.toString());
Oddly, other examples I have seen, including working examples, show that
console.log(range);
will dump the text, however that does not work in my project, I just get the word 'Range', which is the type of the object. This concerns me.
However, all I really need however is a start and end offset in the editor's markup (editor.value()) then I can locate and change the p's to br's.
I've read the telerik documentation and the referenced quirksmode site's explanation of html ranges, and while informative nothing shows how to locate the range withing the text (which seems pretty basic to me).
I suspect I'm overlooking something simple.
Given a range object how can I locate the start and end offset within the editor's content?
EDIT: After additional research it appears much more complex than I anticipated. It seems I must deal with the range and/or selection objects rather than directly with the editor content. Smarter minds than I came up with the range object for reasons I cannot fathom.
Here is what I have so far:
var range = letterEditor.editor.getRange();
var divSelection;
divSelection = range.cloneRange();
//cloning may be needless extra work...
//here manipulate the divSelection to how I want it.
//divSeletion is a range, not sure how to manipulate it
var sel = letterEditor.editor.getSelection()
sel.removeAllRanges();
sel.addRange(divSelection);
EDIT 2:
Based on Tim Down's Solution I came up with this simple test:
var html;
var sel = letterEditor.editor.getSelection();
if (sel.rangeCount) {
var container = document.createElement("div");
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
container.appendChild(sel.getRangeAt(i).cloneContents());
}
html = container.innerHTML;
}
html = html.replace("</p><p>", "<br/>")
var range = letterEditor.editor.getRange();
range.deleteContents();
var div = document.createElement("div");
div.innerHTML = html;
var frag = document.createDocumentFragment(), child;
while ((child = div.firstChild)) {
frag.appendChild(child);
}
range.insertNode(frag);
The first part, getting the html selection works fine, the second part also works however the editor inserts tags around all lines so the result is incorrect; extra lines including fragments of the selection.
The editor supports a view html popup which shows the editor content as html and it allows for editing the html. If I change the targeted p tags to br's I get the desired result. (The editor does support br as a default line feed vs p, but I want p's most of the time). That I can edit the html with the html viewer tool lets me know this is possible, I just need identify the selection start and end in the editor content, then a simple textual replacement via regex on the editor value would do the trick.
Edit 3:
Poking around kendo.all.max.js I discovered that pressing shift+enter creates a br instead of a p tag for the line feed. I was going to extend it to do just that as a workaround for the single-space tool. I would still like a solution to this if anyone knows, but for now I will instruct users to shift-enter for single spaced blocks of text.
This will accomplish it. Uses Tim Down's code to get html. RegEx could probably be made more efficient. 'Trick' is using split = false in insertHtml.
var sel = letterEditor.editor.getSelection();
if (sel.rangeCount) {
var container = document.createElement("div");
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
container.appendChild(sel.getRangeAt(i).cloneContents());
}
var block = container.innerHTML;
var rgx = new RegExp(/<br class="k-br">/gi);
block = block.replace(rgx, "");
rgx = new RegExp(/<\/p><p>/gi);
block = block.replace(rgx, "<br/>");
rgx = new RegExp(/<\/p>|<p>/gi);
block = block.replace(rgx, "");
letterEditor.editor.exec("insertHtml", { html: block, split: false });
}

ActiveReports as a convert to pdf machine

The company I'm with is likely to obtain an ActiveReports 7 license. There's a new project requirement that several webgrids (not actually webgrids, but more like html rendered with zurb) need to be converted into pdfs. At one point in the code behind they're effectively datasets or can be created into such. Is there a way to shuttle the data from the datasets into active reports, then render it out as a PDF. I'd like to keep the report as generic as possible, and thus have one active report for all the datatables, so doing using active reports as its usually done is kind of out of the question.
The only thing I can think of at the moment is a single textbox in the group header into which I could concatenate all the headers, and a single textbox in the details into which I could throw all the data for each row. The problem here is that I'd run into many formatting issues as nothing would line up properly - as tab delimiting would solve nothing here. I could have multiple textboxes with various spacing, but then it would eventually devolve into a different report for each dataset. Is it possible to apply some sort of markup so that I could keep the spacing of columns as I feed the data in. Do active reports richtextboxes honor html markup? Or is there another solution altogether?
I'd use Itextsharp, but its not free for commercial products.
Thanks,
Sam
You can dynamically build a report that will output a simple table based on a specified DataSet, well actually a System.Data.DataTable. Basically for each column in the DataTable, add a textbox to the header to hold the name of the column and add another textbox to the Detail section to hold the value.
For the textbox in the detail section set its DataField property to the name of the column. With the binding in place, you can set the report's DataSource property to the DataTable and then run the report and export it to PDF.
The following code is a basic example:
var left = 0f;
var width = 1f;
var height = .25f;
var space = .25f;
var rpt = new SectionReport();
rpt.Sections.Add(SectionType.ReportHeader, "rh").Height = height;
rpt.Sections.Add(SectionType.Detail, "detail").Height = height;
rpt.Sections.Add(SectionType.ReportFooter, "rf").Height = height;
foreach (System.Data.DataColumn col in dataTable.Columns)
{
var txt = new TextBox { Location = new PointF(left, 0), Size = new SizeF(width, height) };
txt.Text = col.ColumnName;
rpt.Sections["rh"].Controls.Add(txt);
txt = new TextBox { Location = new PointF(left, 0), Size = new SizeF(width, height) };
txt.DataField = col.ColumnName;
rpt.Sections["detail"].Controls.Add(txt);
left += width + space;
}
rpt.DataSource = dataTable;
rpt.Run();
var pdf = new PdfExport();
pdf.Export(rpt.Document, #"c:\Users\scott\downloads\test.pdf");

Break line in long label text

Is there any trick to break a label text? Because '\n' '\r' '\n\r' don't work.
Many Thanks
if you use those 2 parameters you do what you want don't you ?
app.createLabel(text).setWidth(width).setWordWrap(true)
here is an example (among other widgets ;-):
function showurl() {
var app = UiApp.createApplication();
app.setTitle("Anchor in a popup ;-)");
var panel = app.createFlowPanel()
var image = app.createImage('https://sites.google.com/site/appsscriptexperiments/home/photo.jpg').setPixelSize(50, 50)
var link = app.createAnchor('This is your link', 'https://sites.google.com/site/appsscriptexperiments/home');
var lab = app.createLabel("wrap it because it's too narrow").setWidth(90).setWordWrap(true);
var quit = app.createButton('quit');
panel.add(image).add(link).add(lab).add(quit);
app.add(panel);
var doc = SpreadsheetApp.getActive();
doc.show(app);
}
EDIT : I found an old post(on the Google group forum, thanks again Henrique ;-) about breaking lines in toast messages and here is the code I used for that case... the principle should work for Labels too but I didn't try.
To use it, just use \n (where you want to break the line) in a variable containing your text and pass it through this function. (there are some comment in the script to explain)
function break_(msg){
var temp = escape(msg);// shows codes of all chars
msg = unescape(temp.replace(/%20/g,"%A0")); // replace spaces by non break spaces
temp = msg.replace("\n"," "); // and replace the 'newline' by a normal space
return temp; // send back the result
}
Would something like this work?
//takes a line of text and returns a flex table broken by \n
function breakLabel(text) {
var app = UiApp.getActiveApplication();
var flexTable = app.createFlexTable();
text = text.split('\n'); // split into an array
for (var i=0; i<text.length; i++){
flexTable.setWidget(i, 0, app.createLabel(text[i].toString()));
}
return flexTable;
}
Adding them to a vertical panel helps as well (not the way you want, but still..):
var vPanel = app.createVerticalPanel().setSize(100,100);
var label = app.createLabel('predominantly blabla blala blabla');
app.add(vPanel.add(label));
See reference
For anyone just now stumbling upon this, the best solution seems to be creating an HTML output for anything that needs line breaks.
Documentation
var htmlApp = HtmlService
.createHtmlOutput('<p>A change of speed, a change of style...</p>')
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setTitle('My HtmlService Application')
.setWidth(250)
.setHeight(300);
SpreadsheetApp.getActiveSpreadsheet().show(htmlApp);
// The script resumes execution immediately after showing the dialog.

Create Excel Add-in - get cell value

I am creating a excel Add-in using visual studio 2010. I was able to get the cell address using this code.
label1.Label = Globals.MyAddIn.Application.ActiveCell.Address.ToString();
I want to get the cell value. Also if you can tell me how to set a value for a given cell.
Please help.
to get a cell value for the active cell the following should do it
var cellValue = Globals.MyAddIn.Application.ActiveCell.Value.ToString()
or for a specific cell
var cellValue = Globals.MyAddIn.Application.Cells("A1").Value.ToString()
To Set the value it is basically the reverse
Globals.MyAddIn.Application.Cells("A1").Value = "ABC123"
EDIT
Try this. I know that this works as I have something like it working in my own addin.
int row = 1;
int col = 1;
var sheet1 = (Excel.Worksheet)Application.ActiveWorkbook.Worksheets["Sheet1"];
sheet1.Cells[row, col] = "ABC123";
string cellValue = sheet1.Cells[row,col];

Resources