java.lang.illegalstateexception: 'current page not finished!' - c#

after all my trials to create a pdf with a table that contains Arabic text using itext7 failed, I decided to move to the normal way, where I use view.draw and save the result in a pdf. but this also didn't work. here's the code:
Android.Graphics.Pdf.PdfDocument pdf_new = new Android.Graphics.Pdf.PdfDocument();
Android.Graphics.Pdf.PdfDocument.PageInfo pageInfo_new = new Android.Graphics.Pdf.PdfDocument.PageInfo.Builder(6000, 6000, 0).Create();
Android.Graphics.Pdf.PdfDocument.Page page_new = pdf_new.StartPage(pageInfo_new);
ListView listView = new ListView(this.Context);
accounts_info_homeadapter hmm = new accounts_info_homeadapter(this, pdflist);
listView.Adapter = hmm;
listView.SetBackgroundColor(Android.Graphics.Color.Aqua);
listView.Draw(page_new.Canvas);
// lst.Draw(page.Canvas);
//TextView txt = new TextView(this.Context);
//txt.Text = "hi";
//txt.Draw(page.Canvas);
var path = global::Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
file_Path = Path.Combine(path.ToString(), "Client.pdf");
new_stream = new FileStream(file_Path, FileMode.Create);
new_stream.Flush();
pdf_new.WriteTo(new_stream);
new_stream.Close();
pdf_new.Close();
I got the exception: java.lang.illegalstateexception: 'current page not finished!' though I tried this a week ago on a trial list and it was working. now i'm getting this. I thought it might be the size of the pdf so I started increasing it but in vain. I tried changing my variables' names, I thought maybe because I tried to use them with my itext before, but still nothing. I deleted the fragment I 'm working on and then recreated it, also nothing. anyone know what the problem is. thanks in advance.

You missed one line. You forgot to close the page after editing it.
pdf_new.finishPage(page_new)

You must finish the page by calling finishPage(page) before closing the page otherwise it will throw an exception.
From close() docs reference:
Do not call this method if the page returned by startPage(android.graphics.pdf.PdfDocument.PageInfo) is not finished by calling finishPage(android.graphics.pdf.PdfDocument.Page).
In your case it should be:
pdf_new.finishPage(page_new);
pdf_new.close();
Source: close() method docs reference

After inserting your desired text in the canvas make sure to place this line of code.
This helped me to remove my error
canvas.drawText("Financial Statement for 2021",40,50,myPaint);
myPdfDocument.finishPage(myPage1); //this one

Related

Why is the Url value in C# WebBrowser always null?

I am trying to load a local HTML file into an instance of C# WebBrowser (WinForms).
This is what I am doing:
string url = #"file:///C:MyHtml/hello.html";
myWebbrowser.Url = new Uri(url, UriKind.Absolute);
object test = myWebbrowser.Url; // breakpoint here
The path above is correct; if I copy it and paste into an external browser, the file is immediately opened. But the instance of WebBrowser does not want to react. I set a breakpoint in the last line of the snippet, and what I get there is that myWebbrowser.Url is null (the test variable). The control remains correspondingly empty.
myWebbrowser.AllowNavigation is explicitly set to true. I have also tried all possible versions of slashes and backslashes; the result is always the same. The version of the webbrowser seems to be 11 (myWebbrowser.Version = "{11.0.18362.1139}"). I am working in Windows 10, VS 2019.
What can be wrong in this setup?
The path above is correct; if I copy it and paste into an external browser, the file is immediately opened. But the instance of WebBrowser does not want to react. I set a breakpoint in the last line of the snippet, and what I get there is that myWebbrowser.Url is null.
I was able to replicate this exact issue, it's because the property of the Url doesn't get actually set until the document has actually finished loading.
To resolve this issue, you must handle the DocumentCompleted event. You can do so for example:
string url = #"file:///C:MyHtml/hello.html";
myWebbrowser.DocumentCompleted += MyWebbrowser_DocumentCompleted;
myWebbrowser.Url = new Uri(url, UriKind.Absolute);
Create a new routine to handle the DocumentCompleted event:
private void MyWebbrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
string test = myWebbrowser.Url.ToString();
}
You can also get the Url from the WebBrowserDocumentCompletedEventArgs:
string testUrl = e.Url.ToString();
I am not sure exactly why when setting the Url and then checking it, it is null, I haven't found anything to explain why. My only guess is that it may be an invalid Url and or path, if navigation succeeds then that property is set.
Edit: upon looking at the source for WebBrowserDocumentCompleted, it does seem the Url property is only set in the DocumentCompleted, you can see more there.
Please note: you must register the DocumentCompleted event first before setting the Url property as when you do, it will navigate first and you will not receive the DocumentCompleted event.
I was able to find out why it did not want to function, at least I hope so. The "hello.html" file contained calls to jquery and THREE.js, while WebBroser seems not to support the latter. Therefore I did not see any content in the control. After I threw out THREE.js and inserted most simple HTML code, it worked just OK! Now I am busy trying to bring WebBrowser to support THREE.js (there exists a skeptical opinion about this, though).

Revit API - Exception thrown: 'Autodesk.Revit.Exceptions.InternalException' in RevitAPI.dll - When trying to run button twice

Objective
Hi All, I'm working on making a button in Revit that is meant to add a single viewport to a new sheet and then change the viewport to show a viewTitle instead of being empty or just a line
Error
When I run the button for the first time, everything works except the view title is not set to the loaded family although the view title "line" is showing. My error occurs when I run the button the second time.
This is the error I get when I try to run the button a second time:
Exception thrown: 'Autodesk.Revit.Exceptions.InternalException' in RevitAPI.dll
A managed exception was thrown by Revit or by one of its external applications.
The error occurs at this line :
Viewport newViewPort = Viewport.Create(doc, viewSheet.Id, duplicatedPlan2Copy, new XYZ(location.U, location.V, 0));
Exploration
From what I've researched, the button is trying to access an element that is already being accessed but if I'm changing the scale, I should be able to change the ViewTitle. See references at the bottom of this question
here is some of my code which is in the transaction
FamilySymbol firstSheet = colTitleBlocks.FirstElement() as FamilySymbol;
ViewSheet viewSheet = ViewSheet.Create(doc, firstSheet.Id);
UV location = new UV((viewSheet.Outline.Max.U - viewSheet.Outline.Min.U) / 2,
(viewSheet.Outline.Max.V - viewSheet.Outline.Min.V) / 2);
ElementId duplicatedPlan2Copy = duplicatedPlan.Duplicate(ViewDuplicateOption.WithDetailing);
Viewport newViewPort = Viewport.Create(doc, viewSheet.Id, duplicatedPlan2Copy, new XYZ(location.U, location.V, 0));
Findings
I've found that if I remove this line from my code:
bool elementType = doc.GetElement(newViewPort.GetTypeId()).get_Parameter(BuiltInParameter.VIEWPORT_ATTR_LABEL_TAG).Set(viewTitleIdCommand);
It works and is able to create new sheets and place viewports with the view title line only repeatedly.
Any and all help is appreciated.
This link here shows how having 2 separate transaction commits solved the problem however I tried it and that didn't work. this one shows something similar
Here is a reference to my other related question regarding the button
I suggest that you explore and test your intended functionality manually through the user interface first. Once that is stable and optimised and works as expected, you can move over to automating the same steps programmatically through the Revit API. That will probably help you understand what the problem is in a much more efficient manner than struggling with the API, which just replicates the UI functionality.
I've figured it out. I was initially trying to using the TitleView's elementId loaded in from my LoadFamily class that I had instead of finding the elementId through a Filtered Element Collector.
I'm not sure why that was throwing me an error but it was.

In coded ui how do you correctly retrieve a browser window that contains an embedded Adobe PDF reader in browser

I'am running across this issue when I'm debugging or running my coded UI automation project, where i get the exception labeled "{"COM object that has been separated from its underlying RCW cannot be used." System.Exception {System.Runtime.InteropServices.InvalidComObjectException}" everytime i come from a browser window that contains a pdf reader embedded in it. This happens every time I retrieve the window and try to click back. It barfs when i perform the back method on it. I've tried different things but none has worked including the playback wait.
var hereIsmypdf = ReturnPDFDoc();
public BrowserWindow ReturnPDFDoc()
{
Playback.Wait(1000);
var myPdFdoc = GlobalVariables.Browser;
return myPdFdoc;
}
hereIsmypdf.Back();
The only way i was able to get around this issue was not to use the BrowserWindow class. I ended up using the WinWindow class and just getting the tab of the window from it. The BrowserWindow class seemed to trigger the exception "COM object that has been separated from its underlying RCW cannot be used." System.Exception {System.Runtime.InteropServices.InvalidComObjectException}" everytime i tried to retrieve it. I hope this helps someone one or maybe someone has a better way to handle this issue.
For the people that voted my question down, i really did try to figure it out. Sorry i wasnt clear about what i was asking the community or couldn't properly articulate what this pain was. I'm sure someone probably is going through the same pain i did and having a hard time articulating whats going on.
Here is my code on what i ended up doing
public WinTabPage ReturnPDFDoc()
{
WinWindow Wnd = new WinWindow();
Wnd.SearchProperties[BrowserWindow.PropertyNames.ClassName] = "IEFrame";
WinTabList tabRoWlist = new WinTabList(Wnd);
tabRoWlist.SearchProperties[WinTabPage.PropertyNames.Name] = "Tab Row";
WinTabPage myTab = new WinTabPage(tabRoWlist);
myTab.SearchConfigurations.Add(SearchConfiguration.AlwaysSearch);
myTab.SearchProperties[WinTabPage.PropertyNames.Name] = "something";
//UITestControlCollection windows = newWin.FindMatchingControls();
return myTab;
}

Webbrowser control is not showing Html but shows webpage

I am automating a task using webbrowser control , the site display pages using frames.
My issue is i get to a point , where i can see the webpage loaded properly on the webbrowser control ,but when it gets into the code and i see the html i see nothing.
I have seen other examples here too , but all of those do no return all the browser html.
What i get by using this:
HtmlWindow frame = webBrowser1.Document.Window.Frames[1];
string str = frame.Document.Body.OuterHtml;
Is just :
The main frame tag with attributes like SRC tag etc, is there any way how to handle this?Because as i can see the webpage completely loaded why do i not see the html?AS when i do that on the internet explorer i do see the pages source once loaded why not here?
ADDITIONAL INFO
There are two frames on the page :
i use this to as above:
HtmlWindow frame = webBrowser1.Document.Window.Frames[0];
string str = frame.Document.Body.OuterHtml;
And i get the correct HTMl for the first frame but for the second one i only see:
<FRAMESET frameSpacing=1 border=1 borderColor=#ffffff frameBorder=0 rows=29,*><FRAME title="Edit Search" marginHeight=0 src="http://web2.westlaw.com/result/dctopnavigation.aspx?rs=WLW12.01&ss=CXT&cnt=DOC&fcl=True&cfid=1&method=TNC&service=Search&fn=_top&sskey=CLID_SSSA49266105122&db=AK-CS&fmqv=s&srch=TRUE&origin=Search&vr=2.0&cxt=RL&rlt=CLID_QRYRLT803076105122&query=%22LAND+USE%22&mt=Westlaw&rlti=1&n=1&rp=%2fsearch%2fdefault.wl&rltdb=CLID_DB72585895122&eq=search&scxt=WL&sv=Split" frameBorder=0 name=TopNav marginWidth=0 scrolling=no><FRAME title="Main Document" marginHeight=0 src="http://web2.westlaw.com/result/dccontent.aspx?rs=WLW12.01&ss=CXT&cnt=DOC&fcl=True&cfid=1&method=TNC&service=Search&fn=_top&sskey=CLID_SSSA49266105122&db=AK-CS&fmqv=s&srch=TRUE&origin=Search&vr=2.0&cxt=RL&rlt=CLID_QRYRLT803076105122&query=%22LAND+USE%22&mt=Westlaw&rlti=1&n=1&rp=%2fsearch%2fdefault.wl&rltdb=CLID_DB72585895122&eq=search&scxt=WL&sv=Split" frameBorder=0 borderColor=#ffffff name=content marginWidth=0><NOFRAMES></NOFRAMES></FRAMESET>
UPDATE
The two url of the frames are as follows :
Frame1 whose html i see
http://web2.westlaw.com/nav/NavBar.aspx?RS=WLW12.01&VR=2.0&SV=Split&FN=_top&MT=Westlaw&MST=
Frame2 whose html i do not see:
http://web2.westlaw.com/result/result.aspx?RP=/Search/default.wl&action=Search&CFID=1&DB=AK%2DCS&EQ=search&fmqv=s&Method=TNC&origin=Search&Query=%22LAND+USE%22&RLT=CLID%5FQRYRLT302424536122&RLTDB=CLID%5FDB6558157526122&Service=Search&SRCH=TRUE&SSKey=CLID%5FSSSA648523536122&RS=WLW12.01&VR=2.0&SV=Split&FN=_top&MT=Westlaw&MST=
And the properties of the second frame whose html i do not get are in the picture below:
Thank you
I paid for the solution of the question above and it works 100 %.
What i did was use this function below and it returned me the count to the tag i was seeking which i could not find :S.. Use this to call the function listed below:
FillFrame(webBrowser1.Document.Window.Frames);
private void FillFrame(HtmlWindowCollection hwc)
{
if (hwc == null) return;
foreach (HtmlWindow hw in hwc)
{
HtmlElement getSpanid = hw.Document.GetElementById("mDisplayCiteList_ctl00_mResultCountLabel");
if (getSpanid != null)
{
doccount = getSpanid.InnerText.Replace("Documents", "").Replace("Document", "").Trim();
break;
}
if (hw.Frames.Count > 0) FillFrame(hw.Frames);
}
}
Hope it helps people .
Thank you
For taking html you have to do it that way:
WebClient client = new WebClient();
string html = client.DownloadString(#"http://stackoverflow.com");
That's an example of course, you can change the address.
By the way, you need using System.Net;
This works just fine...gets BODY element with all inner elements:
Somewhere in your Form code:
wb.Url = new Uri("http://stackoverflow.com");
wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wbDocumentCompleted);
And here is wbDocumentCompleted:
void wb1DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
var yourBodyHtml = wb.Document.Body.OuterHtml;
}
wb is System.Windows.Forms.WebBrowser
UPDATE:
The same as for the document, I think that your second frame is not loaded at the time you check for it's content...You can try solutions from this link. You will have to wait for your frames to be loaded in order to see its content.
The most likely reason is that frame index 0 has the same domain name as the main/parent page, while the frame index 1 has a different domain name. Am I correct?
This creates a cross-frame security issue, and the WB control just leaves you high and dry and doesn't tell you what on earth went wrong, and just leaves your objects, properties and data empty (will say "No Variables" in the watch window when you try to expand the object).
The only thing you can access in this situation is pretty much the URL and iFrame properties, but nothing inside the iFrame.
Of course, there are ways to overcome teh cross-frame security issues - but they are not built into the WebBrowser control, and they are external solutions, depending on which WB control you are using (as in, .NET version or pre .NET version).
Let me know if I have correctly identified your problem, and if so, if you would like me to tell you about the solution tailored to your setup & instance of the WB control.
UPDATE: I have noticed that you're doing a .getElementByTagName("HTML")(0).outerHTML to get the HTML, all you need to do is call this on the document object, or the .body object and that should do it. MyDoc.Body.innerHTML should get the the content you want. Also, notice that there are additional iFrames inside these documents, in case that is of relevance. Can you give us the main document URL that has these two URL's in it so we / I can replicate what you're doing here? Also, not sure why you are using DomElement but you should just cast it to the native object it wants to be cast to, either a IHTMLDocument2 or the object you see in the watch window, which I think is IHTMLFrameElement (if i recall correctly, but you will know what i mean once you see it). If you are trying to use an XML object, this could be the reason why you aren't able to get the HTML content, change the object declaration and casting if there is one, and give it a go & let us know :). Now I'm curious too :).

Problem using WebBrowser control as editor

I am currently working on a project where I am using a WebBrowser control as an editor. I have design mode turned on and it seems to be working. The issue im having is when I try to save the Document and load another it pops up the "This document has been modified." message. What I am trying to do is as simple as this
if (frontPage)
{
frontPage = false;
frontContent = webEditor.DocumentText;
webEditor.DocumentText = backContent;
}
else
{
frontPage = true;
backContent = webEditor.DocumentText;
webEditor.DocumentText = frontContent;
}
Like I said everytime I enter some text and run this code it just pops up a message saying its been modified and asks if I want to save. How can I get around this?
You should create the following function:
void ChangeAllowWebBrowserDrop() { webBrowser.AllowWebBrowserDrop = !webBrowser.AllowWebBrowserDrop; }
It should be called every time before you change DocumentText.
You could set
BodyHtml.
Like this:
string newHTMLString="some html";
webBrowser1.Document.Body.InnerHtml = newHTMLString;
Worked for me .
You should create the following function:
void ChangeAllowWebBrowserDrop() {
webBrowser.AllowWebBrowserDrop = !webBrowser.AllowWebBrowserDrop;
}
It should be called every time before you change DocumentText.
better solution is to write empty string before you actually assign your html code:
WebBrowser1.Document.Write(string.Empty);
WebBrowser1.DocumentText = "your code";
I have solved this problem so:
browser.Document.Write(string.Empty);
browser.DocumentText="Your html code";
This is from this link:
http://social.msdn.microsoft.com/Forums/vstudio/en-US/3a9c1965-8559-4972-95e1-da0e86cf87bb/webbrowser-strange-problem
The way Windows Forms load a document stream (used by the DocumentText property) is to navigate away to about:blank, which triggers the document modified message, then load the stream in its DocumentComplete event handler.
Since you already have a document, you can skip the navigation and load the stream into the existing document directly via its IPersistStreamInit interface like Windows Forms does in its DocumentComplete event handler.
Try this webEditor.ScriptErrorsSuppressed = true;
Make sure you have disabled Script Debugging in IE in case you've turned it on.

Categories