Display PDF in Vaadin version 14+ - vaadin14

What is the best way to display PDF file in Vaadin 14? i want to display a pdf file in a dialog, but i'm not sure how to render the pdf files. I saw some post about embedded pdf view,pdf browser and EmbeddedPdfDocument, but i can't tell if they are compatible with 14 or not.Is there a new method to do this?

There is a third party addon to render a PDF in Vaadin 14.
Your can find it here: https://vaadin.com/directory/component/pdf-browser/
That gives you the possibility to render a pdf with this code:
StreamResource streamResource = new StreamResource(
"report.pdf", () -> getClass().getResourceAsStream("/report.pdf")); // file in src/main/resources/
PdfBrowserViewer viewer = new PdfBrowserViewer(streamResource);
viewer.setHeight("100%");
layout.add(viewer);
Alternatively you can do it in same way as it was commonly done in previous Vaadin framework versions, embedding in IFrame (see Show PDF in a Vaadin View ), which could look something like this
StreamResource streamResource = new StreamResource(
getPresenter().createPdfStreamSource(), report.getName() + ".pdf");
StreamRegistration registration = VaadinSession.getCurrent().getResourceRegistry().registerResource(resource);
IFrame iframe = new IFrame(registration.getResourceUri().toString());
iframe.setHEight("100%");
layout.add(iframe);

To do it in Vaadin Flow (without an addon) and in a dialog as requested, I'd like to present the following code for your dialog which can be called like any other class. I had to tweak Jean-Christophe his answer a bit.
public class ManualDialog extends Dialog {
private IFrame iFrame;
private final String fileName = "fileNameAsFoundUnderYourResourceMap";
public ManualDialog() {
this.setHeight("calc(100vh - (2*var(--lumo-space-m)))");
this.setWidth("calc(100vw - (4*var(--lumo-space-m)))");
buildLayout();
}
private void buildLayout() {
// HEADER
HorizontalLayout header = new HorizontalLayout();
header.setMaxHeight("1em");
header.setAlignItems(FlexComponent.Alignment.CENTER);
header.setJustifyContentMode(FlexComponent.JustifyContentMode.BETWEEN);
header.getStyle().set("margin-top", "-1em");
Span caption = new Span(getTranslation("main.download.manual"));
caption.getStyle().set("color", "black");
caption.getStyle().set("font-weight", "bold");
Icon closeIcon = new Icon(VaadinIcon.CLOSE);
closeIcon.setColor(GENERIC_BUTTON_COLOR.getDescription());
Button closeButton = new Button();
closeButton.setIcon(closeIcon);
closeButton.getStyle().set("border", "none");
closeButton.getStyle().set("background", "transparent");
closeButton.addClickListener(click -> this.close());
header.add(caption, closeButton);
this.add(header);
// PDF-VIEW
iFrame = new IFrame();
iFrame.setSizeFull();
StreamResource resource = new StreamResource(fileName, () -> new BufferedInputStream(getClass().getClassLoader().getResourceAsStream(fileName)));
StreamRegistration registration = VaadinSession.getCurrent().getResourceRegistry().registerResource(resource);
iFrame.setSrc(registration.getResourceUri().toString());
this.add(iFrame);
this.open();
}
}

Related

Kentico 12 MVC - Add a Forms selector inside a widget

How do I add a Forms widget inside another widget? I tried using FormZone() within the widget but nothing shows up.
It is not possible to render a Forms widget inside another widget in Kentico 12 MVC.
You will need to upgrade to Kentico Xperience 13 for this functionality - see https://docs.xperience.io/developing-websites/page-builder-development/rendering-widgets-in-code#Renderingwidgetsincode-Renderingwidgets
Technically, you can render a Form inside a Widget in Kentico 12, however it is not officially supported and requires a bit of custom development.
The key is to use IFormProvider and IFormComponentVisibilityEvaluator to get all the Form info so that you can render it manually (in a Controller):
var formInfo = BizFormInfoProvider
.GetBizFormInfo(formName, SiteContext.CurrentSiteName);
string className = DataClassInfoProvider
.GetClassName(formInfo.FormClassID);
var existingBizFormItem = className is null
? null
: BizFormItemProvider
.GetItems(className)?.GetExistingItemForContact(
formInfo, contactContext.ContactGuid);
var formComponents = formProvider
.GetFormComponents(formInfo)
.GetDisplayedComponents(
ContactManagementContext.CurrentContact,
formInfo, existingBizFormItem, visibilityEvaluator);
var settings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
TypeNameHandling = TypeNameHandling.Auto,
StringEscapeHandling = StringEscapeHandling.EscapeHtml
};
var formConfiguration = JsonConvert.DeserializeObject<FormBuilderConfiguration>(
formInfo.FormBuilderLayout, settings);
var prefix = Guid.NewGuid().ToString();
ViewData.TemplateInfo.HtmlFieldPrefix = prefix;
return new FormWidgetViewModel
{
DisplayValidationErrors = true,
FormComponents = formComponents.ToList(),
FormConfiguration = formConfiguration,
FormName = formName,
FormPrefix = prefix,
IsFormSubmittable = true,
SiteForms = new List<SelectListItem>(),
SubmitButtonImage = formInfo.FormSubmitButtonImage,
SubmitButtonText = string.IsNullOrEmpty(formInfo.FormSubmitButtonText)
? ResHelper.GetString("general.submit")
: ResHelper.LocalizeString(formInfo.FormSubmitButtonText)
};
Then you would render the Form Model as an HTML Form using Kentico's Form rendering APIs:
<!-- ~/Views/Form/Form.cshtml -->
#using Kentico.Forms.Web.Mvc;
#using Kentico.Forms.Web.Mvc.Widgets;
#using Kentico.Forms.Web.Mvc.Widgets.Internal
#model FormWidgetViewModel
#{
var config = FormWidgetRenderingConfiguration.Default;
// #Html.Kentico().FormSubmitButton(Model) requires
// this ViewData value to be populated. Normally it
// executes as part of the Widget rendering, but since
// we aren't rendering a Widget, we have to do it manually
ViewData.AddFormWidgetRenderingConfiguration(config);
}
#using (Html.Kentico().BeginForm(Model))
{
#Html.Kentico().FormFields(Model)
#Html.Kentico().FormSubmitButton(Model)
}
You can read about the full configuration and setup in my blog post Kentico EMS: MVC Widget Experiments Part 3 - Rendering Form Builder Forms Without Widgets

Highlight links in a Quick Links web part on SharePoint modern page

We have added 4 "Quick Links" web/app part in one section on a SharePoint modern page. We would like to highlight links under "Quick Links web part 2" and "Quick Links web part 4" only. I have added React modern script editor. How do we archive the above requirement using CSS ? If it is not possible in CSS then we would like to introduce JS. I couldn't find a fixed tag name that I can grab and apply CSS except GUID.
You could try to inject CSS by SPFX.
Check the demo shared by hugoabernier.
Main code:
export default class InjectCssApplicationCustomizer
extends BaseApplicationCustomizer<IInjectCssApplicationCustomizerProperties> {
#override
public onInit(): Promise<void> {
Log.info(LOG_SOURCE, `Initialized ${strings.Title}`);
const cssUrl: string = this.properties.cssurl;
if (cssUrl) {
// inject the style sheet
const head: any = document.getElementsByTagName("head")[0] || document.documentElement;
let customStyle: HTMLLinkElement = document.createElement("link");
customStyle.href = cssUrl;
customStyle.rel = "stylesheet";
customStyle.type = "text/css";
head.insertAdjacentElement("beforeEnd", customStyle);
}
return Promise.resolve();
}
}

How to place svg icon in toolbar

I need to replace all of my png icons with with svg - it is my employee request. I am using FFImageLoading. Some of the icons displayed in Pages are displaying properly but the problem is that I can't display svg icon in toolbar (toolbar item and hamburger icon).
I am using Xamarin.Forms 4.3.0.908675 and Xamarin.FFImageLoading - all in version 2.4.11.982.
My logo.svg is placed in MyProject.EmbeddedFiles.Images.
Here are the code samples I tried:
ToolbarItems.Add(new ToolbarItem
{
IconImageSource = "logo.svg",
Order = ToolbarItemOrder.Primary
});
ToolbarItems.Add(new ToolbarItem
{
IconImageSource = "MyProject.EmbeddedFiles.Images.logo.svg",
Order = ToolbarItemOrder.Primary
});
ToolbarItems.Add(new ToolbarItem
{
IconImageSource = ImageSource.FromResource("MyProject.EmbeddedFiles.Images.test.svg", typeof(App).GetTypeInfo().Assembly),
Order = ToolbarItemOrder.Primary
});
ToolbarItems.Add(new ToolbarItem
{
IconImageSource = new SvgImageSource(ImageSource.FromResource("MyProject.EmbeddedFiles.Images.test.svg", typeof(App).GetTypeInfo().Assembly), 10,10,true),
Order = ToolbarItemOrder.Primary
});
Neither solution works. My solution based on https://github.com/luberda-molinet/FFImageLoading/issues/1105
What am I missing? Is this even possible?

UWP/WinJS: show a html page in a pop-up window

I am working on a JavaScript based UWP app. Now I need to dynamically show a html page(with a url) in a pop-up window.
I did some search, there is a ContentDialog I can probably use:
var object = new WinJS.UI.ContentDialog(element, options);
but I cannot find any JavaScript sample code for it. I couldn't figure out what should I pass as "element" and how I put the html in ContentDialog.
Thanks in advance for any help.
The WinJS playground shows you how to use the ContentDialog: http://winjs.azurewebsites.net/#contentdialog
The element you pass is the Html element you want to initiate as the dialog.
<div id="myDialog">I am the going to be the dialog content.</div>
 
var element = document.getElementById('myDialog');
var options = {
title: 'Main instruction',
primaryCommandText: 'Ok',
secondaryCommandText: 'Cancel'
};
var dialog = new WinJS.UI.ContentDialog(element, options);
If you want to set the dialog content dynamically you can do so with
var webview = document.createElement('x-ms-webview');
webview.src = 'http://stackoverflow.com';
dialog.element.querySelector('.win-contentdialog-content').appendChild(webview);
dialog.show();

Can WatiN handle the CuteWebUI Uploader popup dialog?

My Background:
I am new to WatiN, but not new to writing automated Web UI tests. At my new job, we are trying to use WatiN for our Web UI tests (thanks to a few CUIT fails).
I've solved this problem in the past using ArtOfTest.WebAii, by using a Win32 mouse click with a magic number offset from the containing element, but I can't seem to find documentation on how to do that in WatiN and I can't figure it out myself :\
My problem:
This dialog appears and I can't seem to find a way for WatiN to click it.
The dialog has the following markup:
<OBJECT style="FILTER: alpha(opacity=1); WIDTH: 329px; HEIGHT: 100px; mozOpacity: 0.01; opacity: 0.01; mozopacity: 0.01" data="data:application/x-oleobject;base64, <a bunch of data>" width=329 height=100 type=application/x-silverlight-2></OBJECT>
<param name="source" value="/CuteWebUI_Uploader_Resource.axd?type=file&file=silverlight.xap&_ver=634334311861475176"/>
<param name="windowless" value="true" object="" <=""/>
my test code:
[TestMethod]
public void SomeTest()
{
Settings.MakeNewIeInstanceVisible = true;
Settings.AutoStartDialogWatcher = true;
Settings.AutoMoveMousePointerToTopLeft = false;
using (IE ie2 = new IE())
{
ie2.GoTo(URL);
ie2.Link(SomeButtonID).Click();
ie2.Image(AnotherButtonID).FireEvent("onclick");
// some debugging code wrapped around the next user action
// which is clicking on the attach file button
var helper = new DialogHandlerHelper();
using (new UseDialogOnce(ie2.DialogWatcher, helper))
{
Thread.Sleep(1 * 1000); // wait for attach button to be "ready"
// Click button that triggers the dialog that states:
// "file browsing dialog has been blocked"
// "please click here and try again"
//
ie2.Button(FileAttachButtonID).FireEvent("onclick");
}
foreach(string dialogHandler in helper.CandidateDialogHandlers)
{
// nothing prints out here :(
Console.Out.WriteLine(dialogHandler);
}
// debug print out all elements with tagname = object
foreach (Element objectElement in ie2.ElementsWithTag("object"))
{
StringBuilder elementInfo = new StringBuilder();
elementInfo.AppendLine("--------------------------------------------");
elementInfo.AppendLine("element.tagname = " + objectElement.TagName);
elementInfo.AppendLine("element.style = " + objectElement.Style);
elementInfo.AppendLine("element.type = " + objectElement.GetAttributeValue("type"));
elementInfo.AppendLine("element.data = " + objectElement.GetAttributeValue("data"));
elementInfo.AppendLine("--------------------------------------------");
Console.Out.WriteLine(elementInfo.ToString());
// none of these clicks make the dialog go away
objectElement.ClickNoWait();
objectElement.Click();
objectElement.DoubleClick();
objectElement.MouseEnter();
objectElement.MouseDown();
Thread.Sleep(500);
objectElement.MouseUp();
}
// wait to see if dialog disappears after click
Thread.Sleep(300 * 1000);
}
}
Any and all help will be very much appreciated.
Thanks!
Your control is a silverlight component which can't be automated with WatiN. Fortunately this you can combine WatiN and White to get the job done.
Following code is created and published by Leo Bartnik so ALL the credits go to him! Have a look at his blog post here. The following code in the comments:
He used the following versions.
watin-2.0.50.1179.zip from 2011-02-08 http://sourceforge.net/projects/watin/files/WatiN%202.x/2.0%20Final/
white 0.20 Binaries http://white.codeplex.com/releases/view/29694
public void WatiN_and_White_join_forces()
{
// Navigate to your webpage with WatiN
string url = "http://localhost[port#]/WatinWhiteTestLandingPage.aspx";
WatiN.Core.IE watin = new WatiN.Core.IE(url);
watin.Link(Find.ByText("click here)).Click();
// Attach the IE instance used by WatiN to White
InternetExplorerFactory.Plugin();
string title = "[browser title here]"; // will be something like "WatinWhiteHybrid - Internet Explorer provided by ..."
var ie = (InternetExplorerWindow)Application.Attach(watin.ProcessID).GetWindow(title);
White.WebBrowser.Silverlight.SilverlightDocument sl = ie.SilverlightDocument;
// Click the button in the silverlight control using White
sl.Get(SearchCriteria.ByAutomationId("ClickMeId")).Click();
}
btw don't know why the formating of this code is so way off....
So this was my hack solution:
Use Microsoft's Coded UI Test to click on the Silverlight dialog. However, CUIT is inferior to WatiN, so I run my test in WatiN and load CUIT for one, magical, click.
Additionally, I was not able to easily find the Silverlight object using CUIT, so I find the window behind it, find the window's center pixel and force a Microsoft.VisualStudio.TestTools.UITesting.Mouse.Click(). Yes, a hack inside of a hack, I am a very bad person, but I ran out of time and just needed something working.
If anyone has a more elegant solution, please share.
My solution code:
FileUploadDialogHandler helper = new FileUploadDialogHandler(attachmentPath);
using (new UseDialogOnce(ie.DialogWatcher, helper))
{
Thread.Sleep(1 * 1000); // wait for attach button to be "ready"
ie.Button(browseButtonID).FireEvent("onclick");
// When automating a file upload, there is a Silverlight popup in IE that forces an extra click
// before opening the file open dialog. WatiN does not support Silverlight automation
// and the popup element was acting quirky in Microsoft's Coded UI Test, so we find the
// dialog box UNDERNEATH the Silverlight popup and force one, lovely, mouse click.
//===== Entering Coded UI Test land, beware! =====================================
// initialize Coded UI Test
Playback.Initialize();
BrowserWindow.CurrentBrowser = "IE";
Process watinBrowserProcess = Process.GetProcessById(ie.ProcessID);
BrowserWindow cuitBrowser = BrowserWindow.FromProcess(watinBrowserProcess); // attach Coded UI Test to the IE browser WatiN initialized
// get the window underneath the Silverlight popup
UITestControl modalUnderSilverlightPopup = new UITestControl(cuitBrowser.CurrentDocumentWindow);
modalUnderSilverlightPopup.SearchProperties.Add("id", windowElementUnderPopupID);
// get the X and Y pixel center of the window
int centerX = modalUnderSilverlightPopup.BoundingRectangle.X + modalUnderSilverlightPopup.BoundingRectangle.Width / 2;
int centerY = modalUnderSilverlightPopup.BoundingRectangle.Y + modalUnderSilverlightPopup.BoundingRectangle.Height / 2;
// Click!
Mouse.Click(new Point(centerX, centerY));
// Shutdown Coded UI Test
Playback.Cleanup();
//===== End Coded UI Test land, you survived! yay! ============================
}

Resources