Merge pull request #2125 from mmsharepoint/MMDev

Added react-teams-graph-upload-as-pdf sample
This commit is contained in:
Hugo Bernier 2021-11-18 03:03:58 -05:00 committed by GitHub
commit 3b86c93ff3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
34 changed files with 26320 additions and 4 deletions

View File

@ -20,7 +20,7 @@ or good old where's Wally game 😉
## Compatibility
![SPFx 1.13.0](https://img.shields.io/badge/SPFx-1.13.0-green.svg)
![Node.js v14 | v12 | v10](https://img.shields.io/badge/Node.js-v14%20%7C%20v12%20%7C%20v10-green.svg)
![Node.js v14 | v12](https://img.shields.io/badge/Node.js-v14%20%7C%20v12-green.svg)
![Compatible with SharePoint Online](https://img.shields.io/badge/SharePoint%20Online-Compatible-green.svg)
![Does not work with SharePoint 2019](https://img.shields.io/badge/SharePoint%20Server%202019-Incompatible-red.svg "SharePoint Server 2019 requires SPFx 1.4.1 or lower")
![Does not work with SharePoint 2016 (Feature Pack 2)](https://img.shields.io/badge/SharePoint%20Server%202016%20(Feature%20Pack%202)-Incompatible-red.svg "SharePoint Server 2016 Feature Pack 2 requires SPFx 1.1")

View File

@ -28,7 +28,7 @@ The web part uses the default columns of the SharePoint Tasks list for showing t
## Compatibility
![SPFx 1.13.0](https://img.shields.io/badge/SPFx-1.13.0-green.svg)
![Node.js v14 | v12 | v10](https://img.shields.io/badge/Node.js-v14%20%7C%20v12%20%7C%20v10-green.svg)
![Node.js v14 | v12](https://img.shields.io/badge/Node.js-v14%20%7C%20v12-green.svg)
![Compatible with SharePoint Online](https://img.shields.io/badge/SharePoint%20Online-Compatible-green.svg)
![Does not work with SharePoint 2019](https://img.shields.io/badge/SharePoint%20Server%202019-Incompatible-red.svg "SharePoint Server 2019 requires SPFx 1.4.1 or lower")
![Does not work with SharePoint 2016 (Feature Pack 2)](https://img.shields.io/badge/SharePoint%20Server%202016%20(Feature%20Pack%202)-Incompatible-red.svg "SharePoint Server 2016 Feature Pack 2 requires SPFx 1.1")

View File

@ -18,7 +18,7 @@ When the user clicks on the header it dynamically load documents.
## Compatibility
![SPFx 1.13.0](https://img.shields.io/badge/SPFx-1.13.0-green.svg)
![Node.js v14 | v12 | v10](https://img.shields.io/badge/Node.js-v14%20%7C%20v12%20%7C%20v10-green.svg)
![Node.js v14 | v12](https://img.shields.io/badge/Node.js-v14%20%7C%20v12-green.svg)
![Compatible with SharePoint Online](https://img.shields.io/badge/SharePoint%20Online-Compatible-green.svg)
![Does not work with SharePoint 2019](https://img.shields.io/badge/SharePoint%20Server%202019-Incompatible-red.svg "SharePoint Server 2019 requires SPFx 1.4.1 or lower")
![Does not work with SharePoint 2016 (Feature Pack 2)](https://img.shields.io/badge/SharePoint%20Server%202016%20(Feature%20Pack%202)-Incompatible-red.svg "SharePoint Server 2016 Feature Pack 2 requires SPFx 1.1")

View File

@ -11,7 +11,7 @@ This SPFx Outlook Add-In lets users save any email attachments to a OneDrive fol
## Compatibility
![SPFx 1.13.0](https://img.shields.io/badge/SPFx-1.13.0-green.svg)
![Node.js v14 | v12 | v10](https://img.shields.io/badge/Node.js-v14%20%7C%20v12%20%7C%20v10-green.svg)
![Node.js v14 | v12](https://img.shields.io/badge/Node.js-v14%20%7C%20v12-green.svg)
![Compatible with SharePoint Online](https://img.shields.io/badge/SharePoint%20Online-Compatible-green.svg)
![Does not work with SharePoint 2019](https://img.shields.io/badge/SharePoint%20Server%202019-Incompatible-red.svg "SharePoint Server 2019 requires SPFx 1.4.1 or lower")
![Does not work with SharePoint 2016 (Feature Pack 2)](https://img.shields.io/badge/SharePoint%20Server%202016%20(Feature%20Pack%202)-Incompatible-red.svg "SharePoint Server 2016 Feature Pack 2 requires SPFx 1.1")

View File

@ -0,0 +1,33 @@
# Logs
logs
*.log
npm-debug.log*
# Dependency directories
node_modules
# Build generated files
dist
lib
release
solution
temp
*.sppkg
# Coverage directory used by tools like istanbul
coverage
# OSX
.DS_Store
# Visual Studio files
.ntvs_analysis.dat
.vs
bin
obj
# Resx Generated Code
*.resx.ts
# Styles Generated Code
*.scss.ts

View File

@ -0,0 +1,16 @@
!dist
config
gulpfile.js
release
src
temp
tsconfig.json
tslint.json
*.log
.yo-rc.json
.vscode

View File

@ -0,0 +1,12 @@
{
"@microsoft/generator-sharepoint": {
"isCreatingSolution": true,
"environment": "spo",
"version": "1.13.0",
"libraryName": "react-teams-graph-upload-as-pdf",
"libraryId": "f10938fa-9fe7-4cb2-bc00-15902a2cfc66",
"packageManager": "npm",
"isDomainIsolated": false,
"componentType": "webpart"
}
}

View File

@ -0,0 +1,97 @@
# Teams Graph Upload as PDF
## Summary
This SPFx web part (or Teams Tab) enables a user to upload a supported file type via drag and drop while the uploaded file will be converted as PDF.
In SharePoint context it uploads to the default drive (library) while in Teams context it uses the current channel as a Folder name in the default drive.
It uses the following capabilities (mostly) on behalf of Microsoft Graph:
* Use HTML5 drag and drop event handling
* Writing normal files smaller 4MB
* Retrieving files with format=pdf conversion
![File upload via drag and drop, progress and result](./assets/UploadAnimated.gif)
A detailed functionality and technical description can be found in the [author's blog post](https://mmsharepoint.wordpress.com/2020/11/10/a-simple-spfx-file-upload-by-dragdrop-including-pdf-conversion/)
## Compatibility
![SPFx 1.13.0](https://img.shields.io/badge/SPFx-1.13.0-green.svg)
![Node.js v14 | v12](https://img.shields.io/badge/Node.js-v14%20%7C%20v12-green.svg)
![Compatible with SharePoint Online](https://img.shields.io/badge/SharePoint%20Online-Compatible-green.svg)
![Does not work with SharePoint 2019](https://img.shields.io/badge/SharePoint%20Server%202019-Incompatible-red.svg "SharePoint Server 2019 requires SPFx 1.4.1 or lower")
![Does not work with SharePoint 2016 (Feature Pack 2)](https://img.shields.io/badge/SharePoint%20Server%202016%20(Feature%20Pack%202)-Incompatible-red.svg "SharePoint Server 2016 Feature Pack 2 requires SPFx 1.1")
![Local Workbench Unsupported](https://img.shields.io/badge/Local%20Workbench-Unsupported-red.svg "Local workbench is no longer available as of SPFx 1.13 and above")
![Hosted Workbench Compatible (with Permissions)](https://img.shields.io/badge/Hosted%20Workbench-Compatible%20(with%20permissions)-yellow.svg)
## Applies to
- [SharePoint Framework](https://aka.ms/spfx)
- [Microsoft 365 tenant](https://docs.microsoft.com/en-us/sharepoint/dev/spfx/set-up-your-developer-tenant)
## Solution
Solution|Author(s)
--------|---------
react-teams-graph-upload-as-pdf| [Markus Moeller](https://github.com/mmsharepoint) ([@moeller2_0](http://www.twitter.com/moeller2_0))
## Version history
Version|Date|Comments
-------|----|--------
1.0|November 10, 2020|Initial release
1.1|November 08, 2021|Updated to SPFx 1.13 & Shared with PnP repo
## Minimal Path to Awesome
- Clone this repository (or download this [solution as a .ZIP file](https://pnp.github.io/download-partial/?url=https://github.com/pnp/sp-dev-fx-webparts/tree/main/samples/react-teams-graph-upload-as-pdf) then unzip it)
- Ensure that you are at the solution folder
- in the command-line run:
- `npm install`
- `gulp bundle --ship`
- `gulp package-solution --ship`
- Upload your package from `/sharepoint/solution/` to your app catalog
- In SharePoint CA approve following web api permissions
- `Files.ReadWrite`
- `Sites.ReadWrite.All`
## Features
This web part illustrates the following concepts:
- Use HTML5 drag and drop event handling
- [Writing normal files smaller 4MB](https://docs.microsoft.com/en-us/graph/api/driveitem-put-content?view=graph-rest-1.0&tabs=http)
- Retrieving files with [format=pdf](https://docs.microsoft.com/en-us/graph/api/driveitem-get-content-format?view=graph-rest-1.0&tabs=http) conversion
- [FluentUI Progress Indicator](https://developer.microsoft.com/en-us/fluentui#/controls/web/progressindicator)
## Alternative
When looking for a robust solution in Microsoft Teams espacially also consider my alternative sample created with the yeoman generator for Teams.
There the up- and download functionality takes place in the backend and not via the frontend (browser).
Of course consider the same code to be combined with a SPFx forntend (only).
(https://github.com/pnp/teams-dev-samples/tree/main/samples/tab-sso-graph-upload-as-pdf)
## Help
We do not support samples, but this community is always willing to help, and we want to improve these samples. We use GitHub to track issues, which makes it easy for community members to volunteer their time and help resolve issues.
If you're having issues building the solution, please run [spfx doctor](https://pnp.github.io/cli-microsoft365/cmd/spfx/spfx-doctor/) from within the solution folder to diagnose incompatibility issues with your environment.
You can try looking at [issues related to this sample](https://github.com/pnp/sp-dev-fx-webparts/issues?q=label%3Areact-teams-graph-upload-as-pdf) to see if anybody else is having the same issues.
You can also try looking at [discussions related to this sample](https://github.com/pnp/sp-dev-fx-webparts/discussions?discussions_q=label%3Areact-teams-graph-upload-as-pdf) and see what the community is saying.
If you encounter any issues while using this sample, [create a new issue](https://github.com/pnp/sp-dev-fx-webparts/issues/new?assignees=&labels=Needs%3A+Triage+%3Amag%3A%2Ctype%3Abug-suspected&template=bug-report.yml&sample=react-teams-graph-upload-as-pdf&authors=@mmsharepoint&title=react-teams-graph-upload-as-pdf%20-%20&labels=react-teams-graph-upload-as-pdf).
For questions regarding this sample, [create a new question](https://github.com/pnp/sp-dev-fx-webparts/issues/new?assignees=&labels=Needs%3A+Triage+%3Amag%3A%2Ctype%3Abug-suspected&template=question.yml&sample=react-teams-graph-upload-as-pdf&authors=@mmsharepoint&title=react-teams-graph-upload-as-pdf%20-%20&labels=react-teams-graph-upload-as-pdf).
Finally, if you have an idea for improvement, [make a suggestion](https://github.com/pnp/sp-dev-fx-webparts/issues/new?assignees=&labels=Needs%3A+Triage+%3Amag%3A%2Ctype%3Abug-suspected&template=suggestion.yml&sample=react-teams-graph-upload-as-pdf&authors=@mmsharepoint&title=react-teams-graph-upload-as-pdf%20-%20&labels=react-teams-graph-upload-as-pdf).
## Disclaimer
**THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.**
<img src="https://telemetry.sharepointpnp.com/sp-dev-fx-webparts/samples/react-teams-graph-upload-as-pdf" />

Binary file not shown.

After

Width:  |  Height:  |  Size: 94 KiB

View File

@ -0,0 +1,50 @@
[
{
"name": "pnp-sp-dev-spfx-web-parts-react-teams-graph-upload-as-pdf",
"source": "pnp",
"title": "Teams Graph Upload as PDF",
"shortDescription": "This SPFx web part (or Teams Tab) enables a user to upload a supported file type via drag and drop while the uploaded file will be converted as PDF",
"url": "https://github.com/pnp/sp-dev-fx-webparts/tree/main/samples/react-teams-graph-upload-as-pdf",
"longDescription": [
"This SPFx web part (or Teams Tab) enables a user to upload a supported file type via drag and drop while the uploaded file will be converted as PDF"
],
"creationDateTime": "2020-11-10",
"updateDateTime": "2021-11-08",
"products": [
"SharePoint",
"Office"
],
"metadata": [
{
"key": "CLIENT-SIDE-DEV",
"value": "React"
},
{
"key": "SPFX-VERSION",
"value": "1.13.0"
}
],
"thumbnails": [
{
"type": "image",
"order": 100,
"url": "https://github.com/pnp/sp-dev-fx-webparts/raw/main/samples/react-teams-graph-upload-as-pdf/assets/UploadAnimated.gif",
"alt": "Web Part Preview"
}
],
"authors": [
{
"gitHubAccount": "mmsharepoint",
"pictureUrl": "https://github.com/mmsharepoint.png",
"name": "Markus Moeller"
}
],
"references": [
{
"name": "Build your first SharePoint client-side web part",
"description": "Client-side web parts are client-side components that run in the context of a SharePoint page. Client-side web parts can be deployed to SharePoint environments that support the SharePoint Framework. You can also use modern JavaScript web frameworks, tools, and libraries to build them.",
"url": "https://docs.microsoft.com/en-us/sharepoint/dev/spfx/web-parts/get-started/build-a-hello-world-web-part"
}
]
}
]

View File

@ -0,0 +1,18 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/config.2.0.schema.json",
"version": "2.0",
"bundles": {
"upload-file-as-pdf-web-part": {
"components": [
{
"entrypoint": "./lib/webparts/uploadFileAsPdf/UploadFileAsPdfWebPart.js",
"manifest": "./src/webparts/uploadFileAsPdf/UploadFileAsPdfWebPart.manifest.json"
}
]
}
},
"externals": {},
"localizedResources": {
"UploadFileAsPdfWebPartStrings": "lib/webparts/uploadFileAsPdf/loc/{locale}.js"
}
}

View File

@ -0,0 +1,7 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/deploy-azure-storage.schema.json",
"workingDir": "./release/assets/",
"account": "<!-- STORAGE ACCOUNT NAME -->",
"container": "react-teams-graph-upload-as-pdf",
"accessKey": "<!-- ACCESS KEY -->"
}

View File

@ -0,0 +1,31 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/package-solution.schema.json",
"solution": {
"name": "react-teams-graph-upload-as-pdf-client-side-solution",
"id": "f10938fa-9fe7-4cb2-bc00-15902a2cfc66",
"version": "1.0.0.0",
"includeClientSideAssets": true,
"skipFeatureDeployment": true,
"isDomainIsolated": false,
"developer": {
"name": "",
"websiteUrl": "",
"privacyUrl": "",
"termsOfUseUrl": "",
"mpnId": ""
},
"webApiPermissionRequests": [
{
"resource": "Microsoft Graph",
"scope": "Files.ReadWrite"
},
{
"resource": "Microsoft Graph",
"scope": "Sites.ReadWrite.All"
}
]
},
"paths": {
"zippedPackage": "solution/react-teams-graph-upload-as-pdf.sppkg"
}
}

View File

@ -0,0 +1,6 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/core-build/serve.schema.json",
"port": 4321,
"https": true,
"initialPage": "https://enter-your-SharePoint-site/_layouts/workbench.aspx"
}

View File

@ -0,0 +1,4 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/write-manifests.schema.json",
"cdnBasePath": "<!-- PATH TO CDN -->"
}

View File

@ -0,0 +1,14 @@
'use strict';
const build = require('@microsoft/sp-build-web');
build.addSuppression(`Warning - [sass] The local CSS class 'ms-Grid' is not camelCase and will not be type-safe.`);
var getTasks = build.rig.getTasks;
build.rig.getTasks = function () {
var result = getTasks.call(build.rig);
result.set('serve', result.get('serve-deprecated'));
return result;
};
build.initialize(require('gulp'));

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,32 @@
{
"name": "react-teams-graph-upload-as-pdf",
"version": "0.0.1",
"private": true,
"main": "lib/index.js",
"scripts": {
"build": "gulp bundle",
"clean": "gulp clean",
"test": "gulp test"
},
"dependencies": {
"@microsoft/sp-core-library": "1.13.0",
"@microsoft/sp-lodash-subset": "1.13.0",
"@microsoft/sp-office-ui-fabric-core": "1.13.0",
"@microsoft/sp-property-pane": "1.13.0",
"@microsoft/sp-webpart-base": "1.13.0",
"office-ui-fabric-react": "7.174.1",
"react": "16.13.1",
"react-dom": "16.13.1"
},
"devDependencies": {
"@microsoft/rush-stack-compiler-3.9": "0.4.47",
"@microsoft/sp-build-web": "1.13.0",
"@microsoft/sp-module-interfaces": "1.13.0",
"@microsoft/sp-tslint-rules": "1.13.0",
"@types/react": "16.9.51",
"@types/react-dom": "16.9.8",
"@types/webpack-env": "1.13.1",
"ajv": "~5.2.2",
"gulp": "4.0.2"
}
}

View File

@ -0,0 +1 @@
// A file is required to be in the root of the /src directory by the TypeScript compiler

View File

@ -0,0 +1,28 @@
export default class Utilities {
private static validExtensions: string[] = ["csv", "doc", "docx", "odp", "ods", "odt", "pot", "potm", "potx", "pps", "ppsx", "ppsxm", "ppt", "pptm", "pptx", "rtf", "xls", "xlsx"];
public static getFileExtension(fileName: string) {
if (fileName.indexOf('.') > 0) {
const extensions = fileName.split('.');
const fileExtension = extensions[extensions.length - 1];
return fileExtension;
}
}
public static getFileNameAsPDF(fileName: string) {
const orgExtension = this.getFileExtension(fileName);
const extensionStarts = fileName.lastIndexOf(orgExtension);
const namePart = fileName.substr(0, extensionStarts);
return namePart + `pdf`;
}
public static validFileExtension(fileName: string) {
const orgExtension = this.getFileExtension(fileName);
if (this.validExtensions.indexOf(orgExtension) > -1) {
return true;
}
else {
return false;
}
}
}

View File

@ -0,0 +1,71 @@
import { MSGraphClientFactory, MSGraphClient } from "@microsoft/sp-http";
export default class GraphService {
private client: MSGraphClient;
public async initialize (serviceScope): Promise<boolean> {
const graphFactory: MSGraphClientFactory = serviceScope.consume(MSGraphClientFactory.serviceKey);
return graphFactory.getClient()
.then((client) => {
this.client = client;
return true;
});
}
public async uploadTmpFileToOneDrive (file: File): Promise<string> {
const apiUrl = `me/drive/root:/TempUpload/${file.name}:/content`;
const response = await this.uploadFile(apiUrl, file);
const fileID = response.id;
return fileID;
}
public async downloadTmpFileAsPDF (fileID: string): Promise<Blob> {
const apiUrl = `me/drive/items/${fileID}/content?format=PDF`;
const response = await this.client
.api(apiUrl)
.responseType('blob')
.get();
return response;
}
// Alternative to responseType "blob"
// var reader = new FileReader();
// reader.onload = (e) => {
// var rawData = reader.result;
// const apiUrl4 = `me/drive/root:/TempUpload/Binary.pdf:/content`;
// this.client
// .api(apiUrl4)
// .put(rawData);
// }
// reader.readAsBinaryString(res2);
public async uploadFileToSiteAsPDF(siteID: string, file: Blob, fileName: string, channelName: string): Promise<string> {
const apiUrl = channelName !== '' ?
`sites/${siteID}/drive/root:/${channelName}/${fileName}:/content`:
`sites/${siteID}/drive/root:/${fileName}:/content`;
const response = await this.uploadFile(apiUrl, file);
return response.webUrl;
}
private async uploadFile(apiUrl: string, file: Blob) {
if (file.size <(4 * 1024 * 1024)) {
const resp = await this.client
.api(apiUrl)
.put(file);
return resp;
}
else {
// File.size>4MB, refer to https://mmsharepoint.wordpress.com/2020/01/12/an-outlook-add-in-with-sharepoint-framework-spfx-storing-mail-with-microsoftgraph/
return null;
}
}
public async deleteTmpFileFromOneDrive(fileID: string) {
const apiUrl = `me/drive/items/${fileID}`;
this.client
.api(apiUrl)
.delete();
}
}

View File

@ -0,0 +1,27 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx/client-side-web-part-manifest.schema.json",
"id": "593257dd-3b84-4989-ae84-ef12ecd04e7d",
"alias": "UploadFileAsPdfWebPart",
"componentType": "WebPart",
// The "*" signifies that the version should be taken from the package.json
"version": "*",
"manifestVersion": 2,
// If true, the component can only be installed on sites where Custom Script is allowed.
// Components that allow authors to embed arbitrary script code should set this to true.
// https://support.office.com/en-us/article/Turn-scripting-capabilities-on-or-off-1f2c515f-5d7e-448a-9fd7-835da935584f
"requiresCustomScript": false,
"supportedHosts": ["SharePointWebPart","TeamsTab"],
"preconfiguredEntries": [{
"groupId": "5c03119e-3074-46fd-976b-c60198311f70", // Other
"group": { "default": "Other" },
"title": { "default": "Upload File as PDF" },
"description": { "default": "Allows to upload a (supported) file to be uploaded, but as PDF format instead of original" },
"officeFabricIconFontName": "PDF",
"properties": {
"description": "Upload File as PDF"
}
}]
}

View File

@ -0,0 +1,74 @@
import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import {
IPropertyPaneConfiguration,
PropertyPaneTextField
} from '@microsoft/sp-property-pane';
import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';
import { initializeIcons } from '@uifabric/icons';
import * as strings from 'UploadFileAsPdfWebPartStrings';
import UploadFileAsPdf from './components/UploadFileAsPdf';
import { IUploadFileAsPdfProps } from './components/IUploadFileAsPdfProps';
export interface IUploadFileAsPdfWebPartProps {
description: string;
}
export default class UploadFileAsPdfWebPart extends BaseClientSideWebPart<IUploadFileAsPdfWebPartProps> {
private teamsChannelName: string = '';
public onInit(): Promise<void> {
initializeIcons();
if (this.context.sdks.microsoftTeams) {
this.teamsChannelName = this.context.sdks.microsoftTeams.context.channelName;
}
return Promise.resolve();
}
public render(): void {
const url: URL = new URL(this.context.pageContext.site.absoluteUrl);
const siteID = `${url.hostname},${this.context.pageContext.site.id},${this.context.pageContext.web.id}`;
const element: React.ReactElement<IUploadFileAsPdfProps> = React.createElement(
UploadFileAsPdf,
{
serviceScope: this.context.serviceScope,
siteID: siteID,
channelName: this.teamsChannelName
}
);
ReactDom.render(element, this.domElement);
}
protected onDispose(): void {
ReactDom.unmountComponentAtNode(this.domElement);
}
protected get dataVersion(): Version {
return Version.parse('1.0');
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
{
header: {
description: strings.PropertyPaneDescription
},
groups: [
{
groupName: strings.BasicGroupName,
groupFields: [
PropertyPaneTextField('description', {
label: strings.DescriptionFieldLabel
})
]
}
]
}
]
};
}
}

View File

@ -0,0 +1,3 @@
export interface IProgressComponentProps {
header: string;
}

View File

@ -0,0 +1,7 @@
import { ServiceScope } from "@microsoft/sp-core-library";
export interface IUploadFileAsPdfProps {
serviceScope: ServiceScope;
siteID: string;
channelName: string;
}

View File

@ -0,0 +1,19 @@
import * as React from 'react';
import { ProgressIndicator } from 'office-ui-fabric-react/lib/ProgressIndicator';
import { IProgressComponentProps } from './IProgressComponentProps';
export const ProgressComponent: React.FunctionComponent<IProgressComponentProps> = (props) => {
const [percentComplete, setPercentComplete] = React.useState(0);
const intervalDelay = 1;
const intervalIncrement = 0.01;
React.useEffect(() => {
if (percentComplete < 0.99) {
setTimeout(() => {setPercentComplete((intervalIncrement + percentComplete) % 1);}, intervalDelay);
}
});
return (
<ProgressIndicator label={props.header} percentComplete={percentComplete} />
);
};

View File

@ -0,0 +1,31 @@
@import '~office-ui-fabric-react/dist/sass/References.scss';
.uploadFileAsPdf {
.fileCanvas {
position: absolute;
top: 10;
border: 1px solid black;
padding: 20px;
width: 100%;
height: 100%;
z-index: 10;
}
.background {
position: relative;
width: 400px;
height: 200px;
.inner {
position: absolute;
top: 45%;
left: 45%;
color: #ccc;
text-align: center;
.icon {
font-size: 80px;
}
}
}
.highlight {
background-color: rgba(211, 211, 211, 0.5);
}
}

View File

@ -0,0 +1,89 @@
import * as React from 'react';
import styles from './UploadFileAsPdf.module.scss';
import { Icon } from 'office-ui-fabric-react/lib/Icon';
import { IUploadFileAsPdfProps } from './IUploadFileAsPdfProps';
import GraphService from '../../../services/graphService';
import Utilities from '../../../services/Utilities';
import { ProgressComponent } from './ProgressComponent';
const UploadFileAsPdf: React.FunctionComponent<IUploadFileAsPdfProps> = (props) => {
const [highlight, setHighlight] = React.useState(false);
const [tmpFileUploaded, setTmpFileUploaded] = React.useState(false);
const [pdfFileDownloaded, setPDFFileDownloaded] = React.useState(false);
const [pdfFileUploadedDeleted, setPDFFileUploadedDeleted] = React.useState(false);
const [pdfFileUploadUrl, setPDFFileUploadUrl] = React.useState('');
const allowDrop = (event) => {
event.preventDefault();
event.stopPropagation();
event.dataTransfer.dropEffect = 'copy';
setTmpFileUploaded(false);
setPDFFileDownloaded(false);
setPDFFileUploadedDeleted(false);
};
const enableHighlight = (event) => {
allowDrop(event);
setHighlight(true);
};
const disableHighlight = (event) => {
allowDrop(event);
setHighlight(false);
};
const dropFile = (event) => {
allowDrop(event);
setHighlight(false);
let dt = event.dataTransfer;
let files = Array.prototype.slice.call(dt.files); //[...dt.files];
files.forEach(fileToUpload => {
if (Utilities.validFileExtension(fileToUpload.name)) {
uploadFile(fileToUpload);
}
});
};
const uploadFile = async (file:File) => {
const graphService: GraphService = new GraphService();
const initialized = await graphService.initialize(props.serviceScope);
if (initialized) {
const tmpFileID = await graphService.uploadTmpFileToOneDrive(file);
setTmpFileUploaded(true);
setTimeout(async () => {
const pdfBlob = await graphService.downloadTmpFileAsPDF(tmpFileID);
setPDFFileDownloaded(true);
const newFilename = Utilities.getFileNameAsPDF(file.name);
const fileUrl = await graphService.uploadFileToSiteAsPDF(props.siteID, pdfBlob, newFilename, props.channelName);
setPDFFileUploadUrl(fileUrl);
graphService.deleteTmpFileFromOneDrive(tmpFileID)
.then(() => {
setTimeout(() => {
setPDFFileUploadedDeleted(true);
}, 1000);
});
}, 800);
}
};
return (
<div className={ styles.uploadFileAsPdf }>
Drag your file here:
<div className={styles.background}>
<div className={`${styles.fileCanvas} ${highlight?styles.highlight:''}`}
onDragEnter={enableHighlight}
onDragLeave={disableHighlight}
onDragOver={allowDrop}
onDrop={dropFile}>
{tmpFileUploaded && <ProgressComponent header="File uploaded temp. to OneDrive" />}
{pdfFileDownloaded && <ProgressComponent header="File retrieved as PDF" />}
{pdfFileUploadUrl !== '' &&
<div>
<ProgressComponent header="File uploaded to target (and temp. file deleted)" />
{pdfFileUploadedDeleted && <div>File uploaded to target and available <a href={pdfFileUploadUrl}>here.</a></div>}
</div>}
</div>
{!tmpFileUploaded && <div className={styles.inner}><Icon className={styles.icon} iconName="PDF" /><br/>To generate a PDF</div>}
</div>
</div>
);
};
export default UploadFileAsPdf;

View File

@ -0,0 +1,7 @@
define([], function() {
return {
"PropertyPaneDescription": "Description",
"BasicGroupName": "Group Name",
"DescriptionFieldLabel": "Description Field"
}
});

View File

@ -0,0 +1,10 @@
declare interface IUploadFileAsPdfWebPartStrings {
PropertyPaneDescription: string;
BasicGroupName: string;
DescriptionFieldLabel: string;
}
declare module 'UploadFileAsPdfWebPartStrings' {
const strings: IUploadFileAsPdfWebPartStrings;
export = strings;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 383 B

View File

@ -0,0 +1,35 @@
{
"extends": "./node_modules/@microsoft/rush-stack-compiler-3.9/includes/tsconfig-web.json",
"compilerOptions": {
"target": "es5",
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"jsx": "react",
"declaration": true,
"sourceMap": true,
"experimentalDecorators": true,
"skipLibCheck": true,
"outDir": "lib",
"inlineSources": false,
"strictNullChecks": false,
"noUnusedLocals": false,
"typeRoots": [
"./node_modules/@types",
"./node_modules/@microsoft"
],
"types": [
"webpack-env"
],
"lib": [
"es5",
"dom",
"es2015.collection",
"ES2015.Promise"
]
},
"include": [
"src/**/*.ts",
"src/**/*.tsx"
]
}

View File

@ -0,0 +1,29 @@
{
"extends": "./node_modules/@microsoft/sp-tslint-rules/base-tslint.json",
"rules": {
"class-name": false,
"export-name": false,
"forin": false,
"label-position": false,
"member-access": false,
"no-arg": false,
"no-console": false,
"no-construct": false,
"no-duplicate-variable": true,
"no-eval": false,
"no-function-expression": true,
"no-internal-module": true,
"no-shadowed-variable": true,
"no-switch-case-fall-through": true,
"no-unnecessary-semicolons": true,
"no-unused-expression": true,
"no-with-statement": true,
"semicolon": true,
"trailing-comma": false,
"typedef": false,
"typedef-whitespace": false,
"use-named-parameter": true,
"variable-name": false,
"whitespace": false
}
}