Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

876081: Export To PDF sample added #87

Merged
merged 2 commits into from
Jun 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions KB-Samples/ExportToPDF/ExportToPDF/App.razor
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<Router AppAssembly="@typeof(App).Assembly">
<Found Context="routeData">
<RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
<FocusOnNavigate RouteData="@routeData" Selector="h1" />
</Found>
<NotFound>
<PageTitle>Not found</PageTitle>
<LayoutView Layout="@typeof(MainLayout)">
<p role="alert">Sorry, there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>

18 changes: 18 additions & 0 deletions KB-Samples/ExportToPDF/ExportToPDF/ExportToPDF.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Syncfusion.Blazor.Diagram" Version="*" />
<PackageReference Include="Syncfusion.PdfExport.Net.Core" Version="*" />
</ItemGroup>

<ItemGroup>
<Folder Include="wwwroot\" />
</ItemGroup>

</Project>
25 changes: 25 additions & 0 deletions KB-Samples/ExportToPDF/ExportToPDF/ExportToPDF.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.4.33122.133
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ExportToPDF", "ExportToPDF.csproj", "{BD607AD5-F5CD-4426-B6CF-BCF6EE5E38A5}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{BD607AD5-F5CD-4426-B6CF-BCF6EE5E38A5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{BD607AD5-F5CD-4426-B6CF-BCF6EE5E38A5}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BD607AD5-F5CD-4426-B6CF-BCF6EE5E38A5}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BD607AD5-F5CD-4426-B6CF-BCF6EE5E38A5}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {E54284AF-9797-4860-9EED-6ECF085DCDBF}
EndGlobalSection
EndGlobal
227 changes: 227 additions & 0 deletions KB-Samples/ExportToPDF/ExportToPDF/Pages/Index.razor
Original file line number Diff line number Diff line change
@@ -0,0 +1,227 @@
@page "/"
@using Syncfusion.PdfExport;

@using Syncfusion.Blazor.Diagram
@using Syncfusion.Blazor.Buttons
@inject IJSRuntime JS;

<SfButton Content="ExportPDF" OnClick="@ExportPDF" />

<SfDiagramComponent @ref="@Diagram" Height="900px" Connectors="@connectors" Nodes="@nodes" NodeCreating="OnNodeCreating" ConnectorCreating="OnConnectorCreating">
</SfDiagramComponent>


@code{
int connectorCount = 0;

public SfDiagramComponent Diagram;
//Defines Diagram's nodes collection
private DiagramObjectCollection<Node> nodes = new DiagramObjectCollection<Node>();

//Defines Diagram's connectors collection
private DiagramObjectCollection<Connector> connectors = new DiagramObjectCollection<Connector>();


protected override void OnInitialized()
{
InitDiagramModel();

}
// Create Nodes and Connectors for the diagram.
private void InitDiagramModel()
{
CreateNode("node1", 300, 80, NodeFlowShapes.Terminator, "Place order");
CreateNode("node2", 300, 160, NodeFlowShapes.Process, "Start transaction");
CreateNode("node3", 300, 240, NodeFlowShapes.Process, "Verification");
CreateNode("node4", 300, 330, NodeFlowShapes.Decision, "Credit card valid?");
CreateNode("node5", 300, 430, NodeFlowShapes.Decision, "Funds available?");
CreateNode("node6", 530, 330, NodeFlowShapes.Process, "Enter payment method");
CreateNode("node7", 300, 530, NodeFlowShapes.Process, "Complete transaction");
CreateNode("node8", 110, 530, NodeFlowShapes.Data, "Send e-mail");
CreateNode("node9", 475, 530, NodeFlowShapes.DirectData, "Customer \n database");
CreateNode("node10", 300, 630, NodeFlowShapes.Terminator, "Log transaction");
CreateNode("node11", 480, 630, NodeFlowShapes.Process, "Reconcile the entries");
CreateConnector("node1", "node2");
CreateConnector("node2", "node3");
CreateConnector("node3", "node4");
CreateConnector("node4", "node5", "Yes");
CreateConnector("node4", "node6", "No", false, "port3", "port1");
CreateConnector("node5", "node6", "No", false, "port3", "port4");
CreateConnector("node5", "node7", "Yes");
CreateConnector("node6", "node2", default(string), false, "port2", "port3");
CreateConnector("node7", "node8");
CreateConnector("node7", "node9");
CreateConnector("node7", "node10");
CreateConnector("node10", "node11", default(string), true);
}

private void OnNodeCreating(IDiagramObject obj)
{
Node node = obj as Node;
node.Style.Fill = "#357BD2";
if (!(node.ID.StartsWith("Annotation") || node.ID.StartsWith("Sequential Data")))
node.Style.StrokeColor = "White";
node.Style.Opacity = 1;
}
private void OnConnectorCreating(IDiagramObject obj)
{
Connector connector = obj as Connector;
connector.Style.Fill = "black";
connector.Style.StrokeColor = "black";
connector.Style.Opacity = 1;
connector.TargetDecorator.Style.Fill = "black";
connector.TargetDecorator.Style.StrokeColor = "black";
}

// used to create a Port.
private DiagramObjectCollection<PointPort> CreatePort()
{
DiagramObjectCollection<PointPort> defaultsPorts = new DiagramObjectCollection<PointPort>();
PointPort port1 = new PointPort()
{
ID = "port1",
Shape = PortShapes.Circle,
Offset = new DiagramPoint() { X = 0, Y = 0.5 }
};
PointPort port2 = new PointPort()
{
ID = "port2",
Shape = PortShapes.Circle,
Offset = new DiagramPoint() { X = 0.5, Y = 0 }
};
PointPort port3 = new PointPort()
{
ID = "port3",
Shape = PortShapes.Circle,
Offset = new DiagramPoint() { X = 1, Y = 0.5 }
};
PointPort port4 = new PointPort()
{
ID = "port4",
Shape = PortShapes.Circle,
Offset = new DiagramPoint() { X = 0.5, Y = 1 }
};
defaultsPorts.Add(port1);
defaultsPorts.Add(port2);
defaultsPorts.Add(port3);
defaultsPorts.Add(port4);
return defaultsPorts;
}
// Method is used to create a Connector for the diagram.
private void CreateConnector(string sourceId, string targetId, string label = default(string), bool isDashLine = false, string sport = "", string tport = "")
{
Connector diagramConnector = new Connector()
{
ID = string.Format("connector{0}", ++connectorCount),
SourceID = sourceId,
TargetID = targetId,
SourcePortID = sport,
TargetPortID = tport
};
if (isDashLine)
{
diagramConnector.Style = new ShapeStyle() { StrokeDashArray = "2,2" };
}
if (label != default(string))
{
var annotation = new PathAnnotation()
{
Content = label,
Style = new TextStyle() { Fill = "white" }
};
if ((sourceId == "node5" && targetId == "node6") || label == "Yes" || label == "No")
{
annotation.Height = 10;
annotation.Width = 15;
}
diagramConnector.Annotations = new DiagramObjectCollection<PathAnnotation>() { annotation };
}
diagramConnector.Type = ConnectorSegmentType.Orthogonal;

connectors.Add(diagramConnector);
}
// Method is used to create a node for the diagram.
private void CreateNode(string id, double x, double y, NodeFlowShapes shape, string label)
{
Node diagramNode = new Node()
{
ID = id,
OffsetX = x,
OffsetY = y,
Width = 145,
Ports = CreatePort(),
Height = 60,
Style = new ShapeStyle { Fill = "#357BD2", StrokeColor = "White" },

Shape = new FlowShape() { Type = Syncfusion.Blazor.Diagram.NodeShapes.Flow, Shape = shape },
Annotations = new DiagramObjectCollection<ShapeAnnotation>
{
new ShapeAnnotation
{
Content = label,
Style = new TextStyle()
{
Color="White", Fill = "transparent"
}
}
}
};
nodes.Add(diagramNode);
}

private async void ExportPDF()
{
DiagramExportSettings print = new DiagramExportSettings();
print.Region = DiagramPrintExportRegion.PageSettings;
print.PageWidth = 500;
print.PageHeight = 800;
print.Orientation = PageOrientation.Portrait;
print.FitToPage = true;
//To export the diagram into base64
var images = await Diagram.ExportAsync(DiagramExportFormat.PNG, print);
var pdforientation = PageOrientation.Portrait == PageOrientation.Landscape ? PdfPageOrientation.Landscape : PdfPageOrientation.Portrait;
await ExportToPdf("diagram", pdforientation, true, images);
}
//
private async Task<string> ExportToPdf(string fileName, PdfPageOrientation orientation, bool allowDownload, string[] images)
{
PdfDocument document = new PdfDocument();
document.PageSettings.Orientation = orientation;
document.PageSettings.Margins = new PdfMargins() { Left = 0, Right = 0, Top = 0, Bottom = 0 };
string base64String;
var dict = images;
for (int i = 0; i < dict.Count(); i++)
{
base64String = dict[i];
using (MemoryStream initialStream = new MemoryStream(Convert.FromBase64String(base64String.Split("base64,")[1])))
{
Stream stream = initialStream as Stream;
PdfPage page = document.Pages.Add();
PdfGraphics graphics = page.Graphics;
#pragma warning disable CA2000
PdfBitmap image = new PdfBitmap(stream);
#pragma warning restore CA2000
graphics.DrawImage(image, 0, 0);
}
}
using (MemoryStream memoryStream = new MemoryStream())
{
document.Save(memoryStream);
memoryStream.Position = 0;
base64String = Convert.ToBase64String(memoryStream.ToArray());
if (allowDownload)
{
await JSRuntimeExtensions.InvokeAsync<string>(JS, "downloadPdf", new object[] { base64String, fileName });
base64String = string.Empty;
}
else
{
base64String = "data:application/pdf;base64," + base64String;
}
document.Dispose();
}
return base64String;
}

}

8 changes: 8 additions & 0 deletions KB-Samples/ExportToPDF/ExportToPDF/Pages/_Host.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
@page "/"
@namespace ExportToPDF.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@{
Layout = "_Layout";
}

<component type="typeof(App)" render-mode="ServerPrerendered" />
25 changes: 25 additions & 0 deletions KB-Samples/ExportToPDF/ExportToPDF/Pages/_Layout.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
@using Microsoft.AspNetCore.Components.Web
@namespace ExportToPDF.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<base href="~/" />
<link rel="stylesheet" href="css/bootstrap/bootstrap.min.css" />
<link href="css/site.css" rel="stylesheet" />
<script src="_content/Syncfusion.Blazor.Core/scripts/syncfusion-blazor.min.js" type="text/javascript"></script>
<link href="ExportToPDF.styles.css" rel="stylesheet" />
<script src="~/interop.js"></script>
<component type="typeof(HeadOutlet)" render-mode="ServerPrerendered" />
</head>
<body>
@RenderBody()



<script src="_framework/blazor.server.js"></script>
</body>
</html>
34 changes: 34 additions & 0 deletions KB-Samples/ExportToPDF/ExportToPDF/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@

using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using Syncfusion.Blazor;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddSyncfusionBlazor();
builder.Services.AddSignalR(e => {
e.MaximumReceiveMessageSize = 102400000;
});
var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}

app.UseHttpsRedirection();

app.UseStaticFiles();

app.UseRouting();

app.MapBlazorHub();
app.MapFallbackToPage("/_Host");

app.Run();
28 changes: 28 additions & 0 deletions KB-Samples/ExportToPDF/ExportToPDF/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:11920",
"sslPort": 44341
}
},
"profiles": {
"ExportToPDF": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7204;http://localhost:5236",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
Loading
Loading