Skip to content

Commit

Permalink
Open and Save for Blazor PDF Viewer next gen commit
Browse files Browse the repository at this point in the history
  • Loading branch information
SaravanaPriya31 authored and SaravanaPriya31 committed Jan 8, 2024
1 parent 5e4a1a0 commit cebef21
Show file tree
Hide file tree
Showing 23 changed files with 693 additions and 0 deletions.
25 changes: 25 additions & 0 deletions Open and Save for Blazor PDF Viewer(next gen)/PDFViewerSample.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.8.34219.65
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PDFViewerSample", "PDFViewerSample\PDFViewerSample.csproj", "{122086AC-F5C1-4E02-A2F7-9FD64A0C9C38}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{122086AC-F5C1-4E02-A2F7-9FD64A0C9C38}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{122086AC-F5C1-4E02-A2F7-9FD64A0C9C38}.Debug|Any CPU.Build.0 = Debug|Any CPU
{122086AC-F5C1-4E02-A2F7-9FD64A0C9C38}.Release|Any CPU.ActiveCfg = Release|Any CPU
{122086AC-F5C1-4E02-A2F7-9FD64A0C9C38}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {58F1D4B3-EEB0-4A76-AC65-81120F954551}
EndGlobalSection
EndGlobal
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<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>
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
namespace PDFViewerSample.Data
{
public class WeatherForecast
{
public DateOnly Date { get; set; }

public int TemperatureC { get; set; }

public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);

public string? Summary { get; set; }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
namespace PDFViewerSample.Data
{
public class WeatherForecastService
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

public Task<WeatherForecast[]> GetForecastAsync(DateOnly startDate)
{
return Task.FromResult(Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = startDate.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
}).ToArray());
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

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

<ItemGroup>
<PackageReference Include="Google.Apis.Drive.v3" Version="1.64.0.3256" />
<PackageReference Include="Syncfusion.Blazor.SfPdfViewer" Version="24.1.44" />
<PackageReference Include="Syncfusion.Blazor.Themes" Version="24.1.44" />
</ItemGroup>

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

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
@page "/counter"

<PageTitle>Counter</PageTitle>

<h1>Counter</h1>

<p role="status">Current count: @currentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

@code {
private int currentCount = 0;

private void IncrementCount()
{
currentCount++;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
@page
@model PDFViewerSample.Pages.ErrorModel

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>Error</title>
<link href="~/css/bootstrap/bootstrap.min.css" rel="stylesheet" />
<link href="~/css/site.css" rel="stylesheet" asp-append-version="true" />
</head>

<body>
<div class="main">
<div class="content px-4">
<h1 class="text-danger">Error.</h1>
<h2 class="text-danger">An error occurred while processing your request.</h2>

@if (Model.ShowRequestId)
{
<p>
<strong>Request ID:</strong> <code>@Model.RequestId</code>
</p>
}

<h3>Development Mode</h3>
<p>
Swapping to the <strong>Development</strong> environment displays detailed information about the error that occurred.
</p>
<p>
<strong>The Development environment shouldn't be enabled for deployed applications.</strong>
It can result in displaying sensitive information from exceptions to end users.
For local debugging, enable the <strong>Development</strong> environment by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>
and restarting the app.
</p>
</div>
</div>
</body>

</html>
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Diagnostics;

namespace PDFViewerSample.Pages
{
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
[IgnoreAntiforgeryToken]
public class ErrorModel : PageModel
{
public string? RequestId { get; set; }

public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);

private readonly ILogger<ErrorModel> _logger;

public ErrorModel(ILogger<ErrorModel> logger)
{
_logger = logger;
}

public void OnGet()
{
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
@page "/fetchdata"
@using PDFViewerSample.Data
@inject WeatherForecastService ForecastService

<PageTitle>Weather forecast</PageTitle>

<h1>Weather forecast</h1>

<p>This component demonstrates fetching data from a service.</p>

@if (forecasts == null)
{
<p><em>Loading...</em></p>
}
else
{
<table class="table">
<thead>
<tr>
<th>Date</th>
<th>Temp. (C)</th>
<th>Temp. (F)</th>
<th>Summary</th>
</tr>
</thead>
<tbody>
@foreach (var forecast in forecasts)
{
<tr>
<td>@forecast.Date.ToShortDateString()</td>
<td>@forecast.TemperatureC</td>
<td>@forecast.TemperatureF</td>
<td>@forecast.Summary</td>
</tr>
}
</tbody>
</table>
}

@code {
private WeatherForecast[]? forecasts;

protected override async Task OnInitializedAsync()
{
forecasts = await ForecastService.GetForecastAsync(DateOnly.FromDateTime(DateTime.Now));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
@using Google.Apis.Drive.v3;
@using Google.Apis.Auth.OAuth2;
@using Google.Apis.Services;
@using Google.Apis.Util.Store;
@using System.IO;
@using System.Threading.Tasks;
@using Syncfusion.Blazor.Buttons
@using Syncfusion.Blazor.SfPdfViewer;

@page "/"
<SfButton @onclick="OnClick">Save file to google drive</SfButton>

<SfPdfViewer2 DocumentPath="@DocumentPath"
@ref="@viewer"
Height="100%"
Width="100%">
</SfPdfViewer2>

@code {
private string DocumentPath { get; set; }
private SfPdfViewer2 viewer;

private readonly string FolderId = "Your Google Drive Folder ID";
private readonly string CredentialPath = "Your Path to the OAuth 2.0 Client IDs json file";
private readonly string ApplicationName = "Your Application name";
private readonly string FileName = "File Name to be loaded into Syncfusion PDF Viewer";

private static readonly string[] Scopes = { DriveService.Scope.DriveFile, DriveService.Scope.DriveReadonly };

protected override async Task OnInitializedAsync()
{
UserCredential credential;
using (var stream1 = new FileStream(CredentialPath, FileMode.Open, FileAccess.Read))
{
string credPath = "token.json";
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream1).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true));
}

var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});

var listRequest = service.Files.List();
listRequest.Q = $"mimeType='application/pdf' and '{FolderId}' in parents and trashed=false";
listRequest.Fields = "files(id, name)";
var files = await listRequest.ExecuteAsync();

string fileIdToDownload = files.Files
.FirstOrDefault(file => file.Name == FileName)?.Id;

if (!string.IsNullOrEmpty(fileIdToDownload))
{
var request = service.Files.Get(fileIdToDownload);
using (var stream = new MemoryStream())
{
await request.DownloadAsync(stream);
stream.Position = 0;
DocumentPath = "data:application/pdf;base64," + Convert.ToBase64String(stream.ToArray());
}
}
else
{
Console.WriteLine("File not found in Google Drive.");
}
}

public async void OnClick(MouseEventArgs args)
{
byte[] data = await viewer.GetDocumentAsync();
string result = Path.GetFileNameWithoutExtension(FileName);
string fileName = result + "_downloaded.pdf";
UserCredential credential;

using (var memStream = new FileStream(CredentialPath, FileMode.Open, FileAccess.Read))
{
string credPath = "token.json";
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(memStream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true));
}

// Create the Drive API service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});

var fileMetadata = new Google.Apis.Drive.v3.Data.File()
{
Name = fileName,
Parents = new List<string> { FolderId }
};

FilesResource.CreateMediaUpload request;

using (var stream = new MemoryStream(data))
{
request = service.Files.Create(fileMetadata, stream, "application/pdf");
request.Fields = "id";
object value = await request.UploadAsync();
}
}
}




Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
@page "/"
@using Microsoft.AspNetCore.Components.Web
@namespace PDFViewerSample.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" />
<link href="PDFViewerSample.styles.css" rel="stylesheet" />
<link rel="icon" type="image/png" href="favicon.png"/>
<component type="typeof(HeadOutlet)" render-mode="ServerPrerendered" />
<!-- Syncfusion Blazor PDF Viewer (Next Gen) control's theme style sheet -->
<link href="_content/Syncfusion.Blazor.Themes/bootstrap5.css" rel="stylesheet" />
<!-- Syncfusion Blazor PDF Viewer (Next Gen) control's scripts -->
<script src="_content/Syncfusion.Blazor.SfPdfViewer/scripts/syncfusion-blazor-sfpdfviewer.min.js" type="text/javascript"></script>
</head>
<body>
<component type="typeof(App)" render-mode="ServerPrerendered" />

<div id="blazor-error-ui">
<environment include="Staging,Production">
An error has occurred. This application may no longer respond until reloaded.
</environment>
<environment include="Development">
An unhandled exception has occurred. See browser dev tools for details.
</environment>
<a href="" class="reload">Reload</a>
<a class="dismiss">🗙</a>
</div>

<script src="_framework/blazor.server.js"></script>
</body>
</html>
Loading

0 comments on commit cebef21

Please sign in to comment.