diff --git a/config/words/_default/config.toml b/config/viewer/_default/config.toml similarity index 100% rename from config/words/_default/config.toml rename to config/viewer/_default/config.toml diff --git a/config/words/production/config.toml b/config/viewer/production/config.toml similarity index 100% rename from config/words/production/config.toml rename to config/viewer/production/config.toml diff --git a/config/words/staging/config.toml b/config/viewer/staging/config.toml similarity index 100% rename from config/words/staging/config.toml rename to config/viewer/staging/config.toml diff --git a/content/home/english/_index.md b/content/home/english/_index.md index 431a67f..3a8ae16 100644 --- a/content/home/english/_index.md +++ b/content/home/english/_index.md @@ -12,7 +12,7 @@ Welcome to our comprehensive collection of tutorials for all GroupDocs Cloud pro ## Document Management Tutorials -### [GroupDocs.Viewer Cloud Tutorials](#) +### [GroupDocs.Viewer Cloud Tutorials](./viewer/) Learn how to render and display over 170 document and image file formats in your applications without requiring additional software or plugins. Our tutorials cover rendering to HTML, PDF, and image formats with various customization options. ### [GroupDocs.Conversion Cloud Tutorials](#) diff --git a/content/viewer/english/_index.md b/content/viewer/english/_index.md new file mode 100644 index 0000000..9b4f391 --- /dev/null +++ b/content/viewer/english/_index.md @@ -0,0 +1,109 @@ +--- +title: GroupDocs.Viewer Cloud Developer Guide Complete Implementation & Integration Tutorial +url: /viewer/ +weight: 2 +description: Comprehensive developer guide for GroupDocs.Viewer Cloud API with step-by-step tutorials, code examples, and best practices for document rendering and visualization. +--- + +# GroupDocs.Viewer Cloud Developer Guide + +## Introduction + +Welcome to the comprehensive developer guide for GroupDocs.Viewer Cloud. This guide provides detailed instructions, code examples, and best practices to help developers integrate and implement document viewing functionality in their applications using GroupDocs.Viewer Cloud API. + +## Getting Started + +### [Getting Started](/viewer/getting-started/) + +Step-by-step tutorials for developers to master GroupDocs.Viewer Cloud API capabilities from basic to advanced features + +### [Document Basic Usage Tutorials](/viewer/basic-usage/) + +Learn to use GroupDocs.Viewer Cloud API with these step-by-step tutorials covering document rendering, HTML, PDF, and image conversion + +### [Document Data Structures Tutorials](/viewer/data-structures/) + +Learn how to use GroupDocs.Viewer Cloud API data structures with these step-by-step tutorials for developers + +### [Document Advanced Usage Tutorials](/viewer/advanced-usage/) + +Comprehensive tutorials for developers to master advanced document viewing features with GroupDocs.Viewer Cloud API, from rendering options to document handling. + +### Prerequisites + +Before starting with GroupDocs.Viewer Cloud implementation, ensure you have: + +- A GroupDocs Cloud account +- API credentials (Client ID and Client Secret) +- Basic understanding of REST APIs +- Familiarity with your preferred programming language + +### Authentication + +All GroupDocs.Viewer Cloud API requests require authentication. The API uses OAuth 2.0 for authentication. Here's how to obtain an access token: + +``` +POST https://api.groupdocs.cloud/connect/token +``` + +## Core Features + +### Document Rendering + +GroupDocs.Viewer Cloud allows rendering documents in various formats: + +- HTML +- PDF +- Image (PNG, JPG) + +### Supported File Formats + +GroupDocs.Viewer Cloud supports over 170 file formats including: + +- Microsoft Office: DOCX, XLSX, PPTX, etc. +- PDF documents +- Images: JPG, PNG, TIFF, etc. +- CAD drawings: DWG, DXF, etc. +- Email formats: MSG, EML, etc. +- And many more + +### Performance Optimization + +Learn techniques to optimize document rendering performance: + +- Page range rendering +- Caching mechanisms +- Resource-efficient rendering options + +## Implementation Scenarios + +This section contains practical usage scenarios of GroupDocs.Viewer Cloud with code examples in multiple programming languages: + +- Document conversion to HTML/PDF/Image +- Watermark application +- Page rotation and reordering +- Text search and extraction +- Responsive document viewing + +## API Reference + +Detailed information about endpoints, request parameters, and response formats for the GroupDocs.Viewer Cloud API. + +## SDK Integration Tutorials + +Step-by-step tutorials for integrating GroupDocs.Viewer Cloud with various programming languages: + +- Node.js +- Java +- .NET +- Python +- PHP +- Ruby + +## Troubleshooting & Best Practices + +Common issues, their solutions, and recommended practices for efficient integration and usage of GroupDocs.Viewer Cloud. + +## Release Notes + +Information about the latest features, improvements, and bug fixes in GroupDocs.Viewer Cloud. diff --git a/content/viewer/english/advanced-usage/_index.md b/content/viewer/english/advanced-usage/_index.md new file mode 100644 index 0000000..d31c18c --- /dev/null +++ b/content/viewer/english/advanced-usage/_index.md @@ -0,0 +1,65 @@ +--- +title: GroupDocs.Viewer Cloud API Document Advanced Usage Tutorials +url: /advanced-usage/ +description: Comprehensive tutorials for developers to master advanced document viewing features with GroupDocs.Viewer Cloud API, from rendering options to document handling. +weight: 10 +--- + +## Introduction to Advanced Viewer Cloud API Tutorials + +Welcome to our comprehensive tutorial series on GroupDocs.Viewer Cloud API's advanced usage features. These hands-on tutorials are designed specifically for developers who want to master the powerful document viewing capabilities offered by GroupDocs.Viewer Cloud. + +Whether you're looking to customize rendering options, handle different document types, or implement advanced viewing features, this tutorial series provides step-by-step guidance to help you achieve real-world solutions with GroupDocs.Viewer Cloud. + +## Learning Path: From Basic to Advanced + +We've organized these tutorials in a progressive learning path to help you build your skills systematically: + +1. Common Rendering Options - Learn fundamental techniques for controlling how documents are rendered +2. Document-Specific Rendering - Master specialized rendering for different document formats +3. Load Options and Advanced Settings - Explore authentication, custom fonts, and other advanced configuration + +## Available Tutorials + +### Common Rendering Options + +- [Tutorial: How to Add Watermarks to Documents](/advanced-usage/add-watermark/) - Learn to overlay text watermarks on documents for copyright protection and branding +- [Tutorial: How to Reorder Document Pages](/advanced-usage/reorder-pages/) - Learn to change the sequence of pages in rendered documents +- [Tutorial: How to Render Hidden Pages](/advanced-usage/render-hidden-pages/) - Master techniques for displaying normally hidden content +- [Tutorial: How to Render Document Notes](/advanced-usage/render-document-with-notes/) - Learn to include presentation notes and other annotations +- [Tutorial: How to Use Custom Fonts](/advanced-usage/render-with-custom-fonts/) - Explore rendering with specific fonts for consistent appearance +- [Tutorial: How to Adjust Image Quality in PDF Documents with GroupDocs.Viewer Cloud](/advanced-usage/adjust-image-quality/) - Learn how to control image quality when rendering PDF documents +-[Tutorial: How to Render Documents with Comments in GroupDocs.Viewer Cloud](/advanced-usage/render-document-with-comments/) - Learn how to control comment rendering in documents with GroupDocs.Viewer Cloud API in this step-by-step tutorial for developers. + +### Document-Specific Rendering Tutorials + +- [Tutorial: Rendering PDF Documents](/advanced-usage/rendering-pdf-documents/) - Learn techniques for rendering PDF documents with optimal quality, adjusting image quality, enabling font hinting, and managing layered content. +- [Tutorial: Spreadsheet Rendering Techniques](/advanced-usage/rendering-spreadsheets/) - Learn advanced Excel and spreadsheet rendering options +- [Tutorial: Word Processing Document Rendering](/advanced-usage/rendering-word-documents/) - Learn advanced Word document rendering options +- [Tutorial: Rendering Outlook Data Files](/advanced-usage/rendering-outlook-files/) - Learn to navigate and render email content from Outlook data files with filtering capabilities. +- [Tutorial: Rendering Text Files](/advanced-usage/rendering-text-files/) - Master the rendering of plain text files with proper formatting and layout control. + +## Prerequisites + +Before beginning these tutorials, you should have: + +1. A GroupDocs.Viewer Cloud account (if you don't have one, [sign up for a free trial](https://dashboard.groupdocs.cloud/#/apps)) +2. Basic knowledge of REST APIs and your preferred programming language +3. Development environment set up for your language of choice (C#, Java, Python, etc.) +4. API credentials (Client ID and Client Secret) from the GroupDocs Cloud Dashboard + +## Helpful Resources + +To support your learning journey, here are some additional resources: + +- [Product Page](https://products.groupdocs.cloud/viewer/) +- [Documentation](https://docs.groupdocs.cloud/viewer/) +- [Live Demo](https://products.groupdocs.app/viewer/family) +- [API Reference UI](https://reference.groupdocs.cloud/viewer/) +- [Blog](https://blog.groupdocs.cloud/categories/groupdocs.viewer-cloud-product-family/) +- [Free Support](https://forum.groupdocs.cloud/c/viewer/9) +- [Free Trial](https://dashboard.groupdocs.cloud/#/apps) + +## Feedback and Questions + +We're committed to helping you succeed with GroupDocs.Viewer Cloud API. If you have questions about these tutorials or need assistance implementing any feature, please visit our [support forum](https://forum.groupdocs.cloud/c/viewer/9) or contact us through the [website](https://products.groupdocs.cloud/viewer/). diff --git a/content/viewer/english/advanced-usage/add-watermark/_index.md b/content/viewer/english/advanced-usage/add-watermark/_index.md new file mode 100644 index 0000000..a32ed19 --- /dev/null +++ b/content/viewer/english/advanced-usage/add-watermark/_index.md @@ -0,0 +1,304 @@ +--- +title: How to Add Watermarks to Documents in GroupDocs.Viewer Cloud Tutorial +url: /advanced-usage/add-watermark/ +description: Learn how to add text watermarks to documents when rendering with GroupDocs.Viewer Cloud API in this step-by-step tutorial for developers. +weight: 20 +--- + +## Tutorial: How to Add Watermarks to Documents + +In this tutorial, you'll learn how to add text watermarks to documents when rendering them with GroupDocs.Viewer Cloud API. Watermarks are useful for indicating document status, protecting copyrighted content, or adding branding to your documents. + +## Learning Objectives + +By the end of this tutorial, you'll be able to: +- Add customized text watermarks to various document formats +- Control watermark position, color, and opacity +- Implement watermarking across different output formats (HTML, PDF, images) +- Apply watermarks to different document types + +## Prerequisites + +Before you begin this tutorial, you need: + +1. A GroupDocs.Viewer Cloud account (if you don't have one, [sign up for a free trial](https://dashboard.groupdocs.cloud/#/apps)) +2. Your Client ID and Client Secret credentials from the GroupDocs Cloud Dashboard +3. Basic understanding of REST APIs +4. Development environment for your preferred language (C#, Java, Python, etc.) +5. [GroupDocs.Viewer Cloud SDK](https://github.com/groupdocs-viewer-cloud) installed for your language of choice + +## The Practical Scenario + +Let's imagine you're developing a document management system where users can view documents but shouldn't be able to claim them as their own. You want to overlay a "CONFIDENTIAL" watermark on all rendered documents to protect sensitive information. + +## Step 1: Understanding Watermark Properties + +GroupDocs.Viewer Cloud allows you to customize various aspects of watermarks: + +- Text - The content of the watermark +- Color - The color of the watermark text (in HTML color format) +- Width - The width of the watermark +- Height - The height of the watermark +- FontName - The name of the font to use +- FontSize - The size of the font +- Position - The position on the page (Diagonal, TopLeft, TopCenter, TopRight, etc.) +- Opacity - The transparency level of the watermark (0-1) + +## Step 2: Set Up Your Project + +First, set up authentication with your Client ID and Client Secret: + +```csharp +// For complete examples and data files, please go to https://github.com/groupdocs-viewer-cloud/groupdocs-viewer-cloud-dotnet-samples +string MyClientSecret = ""; // Get your Client Secret from https://dashboard.groupdocs.cloud +string MyClientId = ""; // Get your Client ID from https://dashboard.groupdocs.cloud + +var configuration = new Configuration(MyClientId, MyClientSecret); +var apiInstance = new ViewApi(configuration); +``` + +## Step 3: Adding a Simple Watermark + +Let's add a basic "CONFIDENTIAL" watermark to a document: + +```csharp +var viewOptions = new ViewOptions +{ + FileInfo = new FileInfo + { + FilePath = "sample.docx" // Document in your cloud storage + }, + ViewFormat = ViewOptions.ViewFormatEnum.HTML, + + // Add a watermark + Watermark = new Watermark + { + Text = "CONFIDENTIAL" + } +}; + +var response = apiInstance.CreateView(new CreateViewRequest(viewOptions)); +``` + +## Step 4: Customizing the Watermark + +Now, let's make our watermark more professional by customizing its appearance: + +```csharp +var viewOptions = new ViewOptions +{ + FileInfo = new FileInfo + { + FilePath = "sample.docx" + }, + ViewFormat = ViewOptions.ViewFormatEnum.HTML, + + // Add a customized watermark + Watermark = new Watermark + { + Text = "CONFIDENTIAL", + Color = "#FF0000", // Red color + FontSize = 48, + Position = Watermark.PositionEnum.Diagonal, + Opacity = 0.5 // 50% opacity + } +}; + +var response = apiInstance.CreateView(new CreateViewRequest(viewOptions)); +``` + +## Step 5: Applying Watermarks to Different Output Formats + +Watermarks work across different output formats. Here's how to add a watermark when rendering to PDF: + +```csharp +var viewOptions = new ViewOptions +{ + FileInfo = new FileInfo + { + FilePath = "sample.docx" + }, + ViewFormat = ViewOptions.ViewFormatEnum.PDF, + + Watermark = new Watermark + { + Text = "CONFIDENTIAL", + Color = "#FF0000", + FontSize = 48, + Position = Watermark.PositionEnum.Diagonal, + Opacity = 0.5 + } +}; + +var response = apiInstance.CreateView(new CreateViewRequest(viewOptions)); +``` + +## Try It Yourself + +Now it's your turn to experiment with watermarks: + +1. Try different watermark positions (Diagonal, TopCenter, BottomRight, etc.) +2. Adjust the opacity to see how it affects readability +3. Change the color and font size to match your branding +4. Apply watermarks to different document types (PDFs, spreadsheets, presentations) + +## Common Issues and Troubleshooting + +Issue: Watermark text is too small or difficult to see +Solution: Increase the font size and adjust opacity for better visibility + +Issue: Watermark position doesn't look right on certain document types +Solution: Different document formats may respond differently to positioning. Test various positions for optimal results. + +Issue: Watermark text appears cut off +Solution: Ensure your watermark text isn't too long. Consider using shorter text or increasing width/height. + +## Complete Code Examples + +### cURL Example + +```bash +# First get JSON Web Token +curl -v "https://api.groupdocs.cloud/connect/token" \ +-X POST \ +-d "grant_type=client_credentials&client_id=xxxx&client_secret=xxxx" \ +-H "Content-Type: application/x-www-form-urlencoded" \ +-H "Accept: application/json" + +# Add watermark to document +curl -v "https://api.groupdocs.cloud/v2.0/viewer/view" \ +-X POST \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +-H "Authorization: Bearer " \ +-d "{ + 'FileInfo': { + 'FilePath': 'sample.docx' + }, + 'ViewFormat': 'HTML', + 'Watermark': { + 'Text': 'CONFIDENTIAL', + 'Color': '#FF0000', + 'FontSize': 48, + 'Position': 'Diagonal', + 'Opacity': 0.5 + } +}" +``` + +### SDK Examples + +#### C# Example + +```csharp +// For complete examples and data files, please go to https://github.com/groupdocs-viewer-cloud/groupdocs-viewer-cloud-dotnet-samples +string MyClientSecret = ""; // Get Client Id and Client Secret from https://dashboard.groupdocs.cloud +string MyClientId = ""; // Get Client Id and Client Secret from https://dashboard.groupdocs.cloud + +var configuration = new Configuration(MyClientId, MyClientSecret); +var apiInstance = new ViewApi(configuration); + +var viewOptions = new ViewOptions +{ + FileInfo = new FileInfo + { + FilePath = "sample.docx" + }, + ViewFormat = ViewOptions.ViewFormatEnum.HTML, + + Watermark = new Watermark + { + Text = "CONFIDENTIAL", + Color = "#FF0000", + FontSize = 48, + Position = Watermark.PositionEnum.Diagonal, + Opacity = 0.5 + } +}; + +var response = apiInstance.CreateView(new CreateViewRequest(viewOptions)); +``` + +#### Python Example + +```python +# For complete examples and data files, please go to https://github.com/groupdocs-viewer-cloud/groupdocs-viewer-cloud-python-samples +import groupdocs_viewer_cloud + +client_id = "XXXX-XXXX-XXXX-XXXX" # Get Client Id and Client Secret from https://dashboard.groupdocs.cloud +client_secret = "XXXXXXXXXXXXXXXX" # Get Client Id and Client Secret from https://dashboard.groupdocs.cloud + +apiInstance = groupdocs_viewer_cloud.ViewApi.from_keys(client_id, client_secret) + +view_options = groupdocs_viewer_cloud.ViewOptions() +view_options.file_info = groupdocs_viewer_cloud.FileInfo() +view_options.file_info.file_path = "sample.docx" +view_options.view_format = "HTML" +view_options.watermark = groupdocs_viewer_cloud.Watermark() +view_options.watermark.text = "CONFIDENTIAL" +view_options.watermark.color = "#FF0000" +view_options.watermark.font_size = 48 +view_options.watermark.position = "Diagonal" +view_options.watermark.opacity = 0.5 + +request = groupdocs_viewer_cloud.CreateViewRequest(view_options) +response = apiInstance.create_view(request) +``` + +#### Java Example + +```java +// For complete examples and data files, please go to https://github.com/groupdocs-viewer-cloud/groupdocs-viewer-cloud-java-samples +String MyClientSecret = ""; // Get Client Id and Client Secret from https://dashboard.groupdocs.cloud +String MyClientId = ""; // Get Client Id and Client Secret from https://dashboard.groupdocs.cloud + +Configuration configuration = new Configuration(MyClientId, MyClientSecret); +ViewApi apiInstance = new ViewApi(configuration); + +FileInfo fileInfo = new FileInfo(); +fileInfo.setFilePath("sample.docx"); +ViewOptions viewOptions = new ViewOptions(); +viewOptions.setFileInfo(fileInfo); +viewOptions.setViewFormat(ViewFormatEnum.HTML); +Watermark watermark = new Watermark(); +watermark.setText("CONFIDENTIAL"); +watermark.setColor("#FF0000"); +watermark.setFontSize(48); +watermark.setPosition(PositionEnum.DIAGONAL); +watermark.setOpacity(0.5); +viewOptions.setWatermark(watermark); + +ViewResult response = apiInstance.createView(new CreateViewRequest(viewOptions)); +``` + +## What You've Learned + +In this tutorial, you've learned: + +- How to add text watermarks to documents when rendering +- Ways to customize watermark appearance including color, position, and opacity +- How to apply watermarks across different output formats +- Techniques for optimizing watermark visibility and appearance + +## Further Practice + +To solidify your knowledge, try these exercises: + +1. Create a document viewer that allows users to toggle watermarks on and off +2. Implement different watermarks based on document sensitivity levels +3. Create a dynamic watermark that includes the current viewer's username +4. Combine watermarking with other rendering options like page selection + +## Helpful Resources + +- [Product Page](https://products.groupdocs.cloud/viewer/) +- [Documentation](https://docs.groupdocs.cloud/viewer/) +- [Live Demo](https://products.groupdocs.app/viewer/family) +- [API Reference UI](https://reference.groupdocs.cloud/viewer/) +- [Blog](https://blog.groupdocs.cloud/categories/groupdocs.viewer-cloud-product-family/) +- [Free Support](https://forum.groupdocs.cloud/c/viewer/9) +- [Free Trial](https://dashboard.groupdocs.cloud/#/apps) + +## Feedback and Questions + +Did you find this tutorial helpful? Do you have questions about implementing watermarks in your application? Let us know in the [GroupDocs.Viewer Cloud forum](https://forum.groupdocs.cloud/c/viewer/9). diff --git a/content/viewer/english/advanced-usage/adjust-image-quality/_index.md b/content/viewer/english/advanced-usage/adjust-image-quality/_index.md new file mode 100644 index 0000000..134d61e --- /dev/null +++ b/content/viewer/english/advanced-usage/adjust-image-quality/_index.md @@ -0,0 +1,342 @@ +--- +title: How to Adjust Image Quality in PDF Documents with GroupDocs.Viewer Cloud Tutorial +url: /advanced-usage/adjust-image-quality/ +description: Learn how to control image quality when rendering PDF documents using GroupDocs.Viewer Cloud API in this step-by-step tutorial for developers. +weight: 30 +--- + +## Tutorial: How to Adjust Image Quality in PDF Documents + +In this tutorial, you'll learn how to adjust the quality of images when rendering PDF documents using GroupDocs.Viewer Cloud API. PDF files often contain images, and controlling their quality is essential for balancing visual fidelity and file size in the rendered output. + +## Learning Objectives + +By the end of this tutorial, you'll be able to: +- Set different image quality levels when rendering PDF documents +- Understand the trade-offs between image quality, file size, and performance +- Implement quality optimization for different use cases +- Apply image quality settings in your applications + +## Prerequisites + +Before you begin this tutorial, you need: + +1. A GroupDocs.Viewer Cloud account (if you don't have one, [sign up for a free trial](https://dashboard.groupdocs.cloud/#/apps)) +2. Your Client ID and Client Secret credentials from the GroupDocs Cloud Dashboard +3. Basic understanding of REST APIs +4. Development environment for your preferred language (C#, Java, Python, etc.) + +## The Practical Scenario + +Imagine you're building a document management system that needs to render PDF documents for web viewing. Some of your users have limited bandwidth, while others prioritize visual quality. You need to implement a feature that allows adjusting image quality based on user preferences or network conditions. + +## Step 1: Understanding Image Quality Settings + +GroupDocs.Viewer Cloud provides the `ImageQuality` property in the `PdfDocumentOptions` class to control the quality of images in rendered PDF documents. This property accepts three values: + +- Low - Fastest rendering with smallest file size, but lower visual quality +- Medium - Balanced option for most use cases +- High - Best visual quality, but larger file size and slower rendering + +The image quality setting affects how images within the PDF are compressed and rendered. This setting is applicable when rendering to HTML format. + +## Step 2: Set Up Your Project + +First, set up authentication with your Client ID and Client Secret: + +```csharp +// For complete examples and data files, please go to https://github.com/groupdocs-viewer-cloud/groupdocs-viewer-cloud-dotnet-samples +string MyClientSecret = ""; // Get your Client Secret from https://dashboard.groupdocs.cloud +string MyClientId = ""; // Get your Client ID from https://dashboard.groupdocs.cloud + +var configuration = new Configuration(MyClientId, MyClientSecret); +var apiInstance = new ViewApi(configuration); +``` + +## Step 3: Rendering PDF with Low Image Quality + +Let's start by rendering a PDF document with low image quality, which is suitable for users with limited bandwidth: + +```csharp +var viewOptions = new ViewOptions +{ + FileInfo = new FileInfo + { + FilePath = "sample.pdf" // PDF document in your cloud storage + }, + ViewFormat = ViewOptions.ViewFormatEnum.HTML, + + RenderOptions = new HtmlOptions + { + PdfDocumentOptions = new PdfDocumentOptions + { + ImageQuality = PdfDocumentOptions.ImageQualityEnum.Low + } + } +}; + +var response = apiInstance.CreateView(new CreateViewRequest(viewOptions)); +``` + +## Step 4: Rendering PDF with Medium Image Quality + +For a balanced approach suitable for most use cases: + +```csharp +var viewOptions = new ViewOptions +{ + FileInfo = new FileInfo + { + FilePath = "sample.pdf" + }, + ViewFormat = ViewOptions.ViewFormatEnum.HTML, + + RenderOptions = new HtmlOptions + { + PdfDocumentOptions = new PdfDocumentOptions + { + ImageQuality = PdfDocumentOptions.ImageQualityEnum.Medium // Balanced quality + } + } +}; + +var response = apiInstance.CreateView(new CreateViewRequest(viewOptions)); +``` + +## Step 5: Rendering PDF with High Image Quality + +For users who prioritize visual quality: + +```csharp +var viewOptions = new ViewOptions +{ + FileInfo = new FileInfo + { + FilePath = "sample.pdf" + }, + ViewFormat = ViewOptions.ViewFormatEnum.HTML, + + RenderOptions = new HtmlOptions + { + PdfDocumentOptions = new PdfDocumentOptions + { + ImageQuality = PdfDocumentOptions.ImageQualityEnum.High // Best quality + } + } +}; + +var response = apiInstance.CreateView(new CreateViewRequest(viewOptions)); +``` + +## Step 6: Implementing Dynamic Quality Selection + +In a real-world application, you might want to select the image quality dynamically based on user preferences or device capabilities: + +```csharp +public ViewResult RenderPdfWithDynamicQuality(string filePath, string qualitySetting) +{ + var viewOptions = new ViewOptions + { + FileInfo = new FileInfo + { + FilePath = filePath + }, + ViewFormat = ViewOptions.ViewFormatEnum.HTML, + + RenderOptions = new HtmlOptions + { + PdfDocumentOptions = new PdfDocumentOptions() + } + }; + + // Set quality based on user preference + switch (qualitySetting.ToLower()) + { + case "low": + viewOptions.RenderOptions.PdfDocumentOptions.ImageQuality = + PdfDocumentOptions.ImageQualityEnum.Low; + break; + case "high": + viewOptions.RenderOptions.PdfDocumentOptions.ImageQuality = + PdfDocumentOptions.ImageQualityEnum.High; + break; + default: + viewOptions.RenderOptions.PdfDocumentOptions.ImageQuality = + PdfDocumentOptions.ImageQualityEnum.Medium; + break; + } + + return apiInstance.CreateView(new CreateViewRequest(viewOptions)); +} +``` + +## Try It Yourself + +Now it's your turn to experiment with PDF image quality settings: + +1. Render the same PDF document with different quality settings and compare the results +2. Measure the file size difference between low, medium, and high quality settings +3. Test with PDFs containing different types of images (photographs, diagrams, charts) +4. Implement a user interface that allows users to select their preferred quality + +## Common Issues and Troubleshooting + +Issue: No noticeable difference in quality despite changing settings +Solution: Some PDFs may not contain images or may have already compressed images. Try with a PDF that contains high-quality photographs. + +Issue: HTML output is very large even with low quality setting +Solution: The PDF might contain many high-resolution images. Consider using additional optimization techniques such as limiting the pages rendered. + +Issue: Image quality setting has no effect +Solution: Ensure you're setting the property on the correct options object and that you're rendering to HTML format. + +## Complete Code Examples + +### cURL Example + +```bash +# First get JSON Web Token +curl -v "https://api.groupdocs.cloud/connect/token" \ +-X POST \ +-d "grant_type=client_credentials&client_id=xxxx&client_secret=xxxx" \ +-H "Content-Type: application/x-www-form-urlencoded" \ +-H "Accept: application/json" + +# Render PDF with medium image quality +curl -v "https://api.groupdocs.cloud/v2.0/viewer/view" \ +-X POST \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +-H "Authorization: Bearer " \ +-d "{ + 'FileInfo': { + 'FilePath': 'sample.pdf' + }, + 'ViewFormat': 'HTML', + 'RenderOptions': { + 'PdfDocumentOptions': { + 'ImageQuality': 'Medium' + } + } +}" +``` + +### SDK Examples + +#### C# Example + +```csharp +// For complete examples and data files, please go to https://github.com/groupdocs-viewer-cloud/groupdocs-viewer-cloud-dotnet-samples +string MyClientSecret = ""; // Get Client Id and Client Secret from https://dashboard.groupdocs.cloud +string MyClientId = ""; // Get Client Id and Client Secret from https://dashboard.groupdocs.cloud + +var configuration = new Configuration(MyClientId, MyClientSecret); +var apiInstance = new ViewApi(configuration); + +var viewOptions = new ViewOptions +{ + FileInfo = new FileInfo + { + FilePath = "sample.pdf" + }, + ViewFormat = ViewOptions.ViewFormatEnum.HTML, + RenderOptions = new HtmlOptions + { + PdfDocumentOptions = new PdfDocumentOptions + { + ImageQuality = PdfDocumentOptions.ImageQualityEnum.Medium + } + } +}; + +var response = apiInstance.CreateView(new CreateViewRequest(viewOptions)); +``` + +#### Python Example + +```python +# For complete examples and data files, please go to https://github.com/groupdocs-viewer-cloud/groupdocs-viewer-cloud-python-samples +import groupdocs_viewer_cloud + +client_id = "XXXX-XXXX-XXXX-XXXX" # Get Client Id and Client Secret from https://dashboard.groupdocs.cloud +client_secret = "XXXXXXXXXXXXXXXX" # Get Client Id and Client Secret from https://dashboard.groupdocs.cloud + +apiInstance = groupdocs_viewer_cloud.ViewApi.from_keys(client_id, client_secret) + +view_options = groupdocs_viewer_cloud.ViewOptions() +view_options.file_info = groupdocs_viewer_cloud.FileInfo() +view_options.file_info.file_path = "sample.pdf" +view_options.view_format = "HTML" +view_options.render_options = groupdocs_viewer_cloud.HtmlOptions() +view_options.render_options.pdf_document_options = groupdocs_viewer_cloud.PdfDocumentOptions() +view_options.render_options.pdf_document_options.image_quality = "Medium" + +request = groupdocs_viewer_cloud.CreateViewRequest(view_options) +response = apiInstance.create_view(request) +``` + +#### Java Example + +```java +// For complete examples and data files, please go to https://github.com/groupdocs-viewer-cloud/groupdocs-viewer-cloud-java-samples +String MyClientSecret = ""; // Get Client Id and Client Secret from https://dashboard.groupdocs.cloud +String MyClientId = ""; // Get Client Id and Client Secret from https://dashboard.groupdocs.cloud + +Configuration configuration = new Configuration(MyClientId, MyClientSecret); +ViewApi apiInstance = new ViewApi(configuration); + +FileInfo fileInfo = new FileInfo(); +fileInfo.setFilePath("sample.pdf"); +ViewOptions viewOptions = new ViewOptions(); +viewOptions.setFileInfo(fileInfo); +viewOptions.setViewFormat(ViewFormatEnum.HTML); +HtmlOptions renderOptions = new HtmlOptions(); +PdfDocumentOptions pdfDocumentOptions = new PdfDocumentOptions(); +pdfDocumentOptions.setImageQuality(ImageQualityEnum.MEDIUM); +renderOptions.setPdfDocumentOptions(pdfDocumentOptions); +viewOptions.setRenderOptions(renderOptions); + +ViewResult response = apiInstance.createView(new CreateViewRequest(viewOptions)); +``` + +## Performance Comparison + +Here's a comparison of the different image quality settings to help you choose the right option for your use case: + +| Quality Setting | File Size | Rendering Speed | Visual Quality | Best For | +|-----------------|-----------|-----------------|----------------|----------| +| Low | Smallest | Fastest | Basic | Mobile devices, slow connections | +| Medium | Moderate | Balanced | Good | Most web applications | +| High | Largest | Slowest | Excellent | Printing, archiving, visual detail | + +## What You've Learned + +In this tutorial, you've learned: + +- How to adjust image quality when rendering PDF documents to HTML +- The different quality levels available and their trade-offs +- How to implement dynamic quality selection based on user preferences +- Ways to optimize PDF rendering for different use cases + +## Further Practice + +To solidify your knowledge, try these exercises: + +1. Build a PDF viewer with a quality selector dropdown (Low, Medium, High) +2. Create an adaptive system that automatically selects quality based on network speed +3. Combine image quality settings with other PDF rendering options +4. Compare file sizes and loading times for different quality settings + +## Helpful Resources + +- [Product Page](https://products.groupdocs.cloud/viewer/) +- [Documentation](https://docs.groupdocs.cloud/viewer/) +- [Live Demo](https://products.groupdocs.app/viewer/family) +- [API Reference UI](https://reference.groupdocs.cloud/viewer/) +- [Blog](https://blog.groupdocs.cloud/categories/groupdocs.viewer-cloud-product-family/) +- [Free Support](https://forum.groupdocs.cloud/c/viewer/9) +- [Free Trial](https://dashboard.groupdocs.cloud/#/apps) + +## Feedback and Questions + +Did you find this tutorial helpful? Do you have questions about implementing image quality controls in your application? Let us know in the [GroupDocs.Viewer Cloud forum](https://forum.groupdocs.cloud/c/viewer/9)! diff --git a/content/viewer/english/advanced-usage/render-document-with-comments/_index.md b/content/viewer/english/advanced-usage/render-document-with-comments/_index.md new file mode 100644 index 0000000..001394a --- /dev/null +++ b/content/viewer/english/advanced-usage/render-document-with-comments/_index.md @@ -0,0 +1,297 @@ +--- +title: How to Render Documents with Comments in GroupDocs.Viewer Cloud Tutorial +url: /advanced-usage/render-document-with-comments/ +description: Learn how to control comment rendering in documents with GroupDocs.Viewer Cloud API in this step-by-step tutorial for developers. +weight: 60 +--- + +## Tutorial: How to Render Documents with Comments + +In this tutorial, you'll learn how to control the rendering of comments in documents using GroupDocs.Viewer Cloud API. By default, comments are hidden when rendering documents, but many collaborative workflows require displaying these comments for review purposes. + +## Learning Objectives + +By the end of this tutorial, you'll be able to: +- Enable comment rendering for supported document types +- Control whether comments appear in the rendered output +- Apply comment rendering settings to various document formats +- Understand which document types support comment rendering + +## Prerequisites + +Before you begin this tutorial, you need: + +1. A GroupDocs.Viewer Cloud account (if you don't have one, [sign up for a free trial](https://dashboard.groupdocs.cloud/#/apps)) +2. Your Client ID and Client Secret credentials from the GroupDocs Cloud Dashboard +3. Basic understanding of REST APIs +4. Development environment for your preferred language (C#, Java, Python, etc.) +5. [GroupDocs.Viewer Cloud SDK](https://github.com/groupdocs-viewer-cloud) installed for your language of choice + +## The Practical Scenario + +Imagine you're developing a document review system where team members collaborate on documents by adding comments and feedback. You need to ensure these comments are visible when the documents are rendered for web viewing, enabling effective collaboration without requiring users to open the original document files. + +## Step 1: Understanding Comment Rendering + +By default, GroupDocs.Viewer Cloud does not render comments when converting documents to HTML, PDF, or images. The API provides a `RenderComments` property that you can set to `true` to include comments in the rendered output. + +This feature is supported for several document types: +- Microsoft Word documents (.docx, .doc) +- PDF documents +- Presentations (.pptx, .ppt) +- Spreadsheets (.xlsx, .xls) + +## Step 2: Set Up Your Project + +First, set up authentication with your Client ID and Client Secret: + +```csharp +// For complete examples and data files, please go to https://github.com/groupdocs-viewer-cloud/groupdocs-viewer-cloud-dotnet-samples +string MyClientSecret = ""; // Get your Client Secret from https://dashboard.groupdocs.cloud +string MyClientId = ""; // Get your Client ID from https://dashboard.groupdocs.cloud + +var configuration = new Configuration(MyClientId, MyClientSecret); +var apiInstance = new ViewApi(configuration); +``` + +## Step 3: Enabling Comment Rendering for Word Documents + +Let's start with a basic example of rendering a Word document with comments: + +```csharp +var viewOptions = new ViewOptions +{ + FileInfo = new FileInfo + { + FilePath = "with_comment.docx" // Document in your cloud storage + }, + ViewFormat = ViewOptions.ViewFormatEnum.HTML, + + RenderOptions = new RenderOptions + { + RenderComments = true // Enable comment rendering + } +}; + +var response = apiInstance.CreateView(new CreateViewRequest(viewOptions)); +``` + +## Step 4: Rendering Comments in PDF Documents + +The same approach works for PDF documents with comments or annotations: + +```csharp +var viewOptions = new ViewOptions +{ + FileInfo = new FileInfo + { + FilePath = "annotated_document.pdf" + }, + ViewFormat = ViewOptions.ViewFormatEnum.HTML, + + RenderOptions = new RenderOptions + { + RenderComments = true + } +}; + +var response = apiInstance.CreateView(new CreateViewRequest(viewOptions)); +``` + +## Step 5: Rendering Comments in Presentations + +For presentation files that contain comments or feedback: + +```csharp +var viewOptions = new ViewOptions +{ + FileInfo = new FileInfo + { + FilePath = "presentation_with_comments.pptx" + }, + ViewFormat = ViewOptions.ViewFormatEnum.HTML, + + RenderOptions = new RenderOptions + { + RenderComments = true + } +}; + +var response = apiInstance.CreateView(new CreateViewRequest(viewOptions)); +``` + +## Step 6: Rendering Comments When Converting to PDF + +You can also enable comment rendering when converting documents to PDF format: + +```csharp +var viewOptions = new ViewOptions +{ + FileInfo = new FileInfo + { + FilePath = "with_comment.docx" + }, + ViewFormat = ViewOptions.ViewFormatEnum.PDF, + + RenderOptions = new RenderOptions + { + RenderComments = true + } +}; + +var response = apiInstance.CreateView(new CreateViewRequest(viewOptions)); +``` + +## Try It Yourself + +Now it's your turn to experiment with comment rendering: + +1. Try rendering the same document with and without comments to see the difference +2. Test with different document types to understand how comments appear in each format +3. Combine comment rendering with other options like watermarking or page selection +4. Implement a toggle in your application to let users choose whether to view comments + +## Common Issues and Troubleshooting + +Issue: Comments aren't appearing despite enabling RenderComments +Solution: Ensure the document actually contains comments. Some comments may be resolved or hidden in the original document. + +Issue: Comment rendering works for one document type but not for another +Solution: Not all document formats support comments. Check if your document type is in the supported list. + +Issue: Comments appear differently than in the original application +Solution: The visual style of rendered comments may differ from the original application's display. This is normal as GroupDocs implements its own comment rendering. + +## Complete Code Examples + +### cURL Example + +```bash +# First get JSON Web Token +curl -v "https://api.groupdocs.cloud/connect/token" \ +-X POST \ +-d "grant_type=client_credentials&client_id=xxxx&client_secret=xxxx" \ +-H "Content-Type: application/x-www-form-urlencoded" \ +-H "Accept: application/json" + +# Render document with comments +curl -v "https://api.groupdocs.cloud/v2.0/viewer/view" \ +-X POST \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +-H "Authorization: Bearer " \ +-d "{ + 'FileInfo': { + 'FilePath': 'with_comment.docx' + }, + 'ViewFormat': 'HTML', + 'RenderOptions': { + 'RenderComments': true + } +}" +``` + +### SDK Examples + +#### C# Example + +```csharp +// For complete examples and data files, please go to https://github.com/groupdocs-viewer-cloud/groupdocs-viewer-cloud-dotnet-samples +string MyClientSecret = ""; // Get Client Id and Client Secret from https://dashboard.groupdocs.cloud +string MyClientId = ""; // Get Client Id and Client Secret from https://dashboard.groupdocs.cloud + +var configuration = new Configuration(MyClientId, MyClientSecret); +var apiInstance = new ViewApi(configuration); + +var viewOptions = new ViewOptions +{ + FileInfo = new FileInfo + { + FilePath = "with_comment.docx" + }, + ViewFormat = ViewOptions.ViewFormatEnum.HTML, + + RenderOptions = new RenderOptions + { + RenderComments = true + } +}; + +var response = apiInstance.CreateView(new CreateViewRequest(viewOptions)); +``` + +#### Python Example + +```python +# For complete examples and data files, please go to https://github.com/groupdocs-viewer-cloud/groupdocs-viewer-cloud-python-samples +import groupdocs_viewer_cloud + +client_id = "XXXX-XXXX-XXXX-XXXX" # Get Client Id and Client Secret from https://dashboard.groupdocs.cloud +client_secret = "XXXXXXXXXXXXXXXX" # Get Client Id and Client Secret from https://dashboard.groupdocs.cloud + +apiInstance = groupdocs_viewer_cloud.ViewApi.from_keys(client_id, client_secret) + +view_options = groupdocs_viewer_cloud.ViewOptions() +view_options.file_info = groupdocs_viewer_cloud.FileInfo() +view_options.file_info.file_path = "with_comment.docx" +view_options.view_format = "HTML" +view_options.render_options = groupdocs_viewer_cloud.HtmlOptions() +view_options.render_options.render_comments = True + +request = groupdocs_viewer_cloud.CreateViewRequest(view_options) +response = apiInstance.create_view(request) +``` + +#### Java Example + +```java +// For complete examples and data files, please go to https://github.com/groupdocs-viewer-cloud/groupdocs-viewer-cloud-java-samples +String MyClientSecret = ""; // Get Client Id and Client Secret from https://dashboard.groupdocs.cloud +String MyClientId = ""; // Get Client Id and Client Secret from https://dashboard.groupdocs.cloud + +Configuration configuration = new Configuration(MyClientId, MyClientSecret); +ViewApi apiInstance = new ViewApi(configuration); + +FileInfo fileInfo = new FileInfo(); +fileInfo.setFilePath("with_comment.docx"); +ViewOptions viewOptions = new ViewOptions(); +viewOptions.setFileInfo(fileInfo); +viewOptions.setViewFormat(ViewFormatEnum.HTML); +RenderOptions renderOptions = new RenderOptions(); +renderOptions.setRenderComments(true); +viewOptions.setRenderOptions(renderOptions); + +ViewResult response = apiInstance.createView(new CreateViewRequest(viewOptions)); +``` + +## What You've Learned + +In this tutorial, you've learned: + +- How to enable comment rendering in documents +- Which document types support comment rendering +- How to configure comment display across different output formats +- Practical applications for comment rendering in collaborative scenarios + +## Further Practice + +To solidify your knowledge, try these exercises: + +1. Build a document review system with a toggle to show/hide comments +2. Create a system that extracts all comments from a document and displays them in a separate panel +3. Implement a feature that highlights text associated with each comment +4. Create a workflow where comments can be filtered by author or date + +## Helpful Resources + +- [Product Page](https://products.groupdocs.cloud/viewer/) +- [Documentation](https://docs.groupdocs.cloud/viewer/) +- [Live Demo](https://products.groupdocs.app/viewer/family) +- [API Reference UI](https://reference.groupdocs.cloud/viewer/) +- [Blog](https://blog.groupdocs.cloud/categories/groupdocs.viewer-cloud-product-family/) +- [Free Support](https://forum.groupdocs.cloud/c/viewer/9) +- [Free Trial](https://dashboard.groupdocs.cloud/#/apps) + +## Feedback and Questions + +Did you find this tutorial helpful? Do you have questions about implementing comment rendering in your application? Let us know in the [GroupDocs.Viewer Cloud forum](https://forum.groupdocs.cloud/c/viewer/9). diff --git a/content/viewer/english/advanced-usage/render-document-with-notes/_index.md b/content/viewer/english/advanced-usage/render-document-with-notes/_index.md new file mode 100644 index 0000000..9086fe9 --- /dev/null +++ b/content/viewer/english/advanced-usage/render-document-with-notes/_index.md @@ -0,0 +1,305 @@ +--- +title: How to Render Documents with Notes in GroupDocs.Viewer Cloud Tutorial +url: /advanced-usage/render-document-with-notes/ +description: Learn how to render presentation notes and other document annotations using GroupDocs.Viewer Cloud API in this step-by-step tutorial for developers. +weight: 70 +--- + +## Tutorial: How to Render Documents with Notes + +In this tutorial, you'll learn how to render documents with notes using GroupDocs.Viewer Cloud API. Notes are particularly common in presentation files, where presenters add speaking points and additional information that isn't shown during the presentation but is valuable for understanding the content. + +## Learning Objectives + +By the end of this tutorial, you'll be able to: +- Enable rendering of notes in presentation files +- Control the visibility of notes in your rendered documents +- Apply note rendering across different output formats +- Understand which document types support note rendering + +## Prerequisites + +Before you begin this tutorial, you need: + +1. A GroupDocs.Viewer Cloud account (if you don't have one, [sign up for a free trial](https://dashboard.groupdocs.cloud/#/apps)) +2. Your Client ID and Client Secret credentials from the GroupDocs Cloud Dashboard +3. Basic understanding of REST APIs +4. Development environment for your preferred language (C#, Java, Python, etc.) +5. [GroupDocs.Viewer Cloud SDK](https://github.com/groupdocs-viewer-cloud) installed for your language of choice + +## The Practical Scenario + +Imagine you're developing a training platform where instructors upload presentations for students. The instructors include detailed notes with each slide to provide context, additional information, and learning prompts. You need to ensure these valuable notes are visible to students when they view the presentations online. + +## Step 1: Understanding Note Rendering + +By default, GroupDocs.Viewer Cloud does not include notes when rendering documents. However, you can enable note rendering by setting the `RenderNotes` property to `true` in your rendering options. + +This feature is primarily designed for: +- PowerPoint presentations (.pptx, .ppt) +- Other presentation formats that support notes + +When enabled, notes will be displayed below each slide in the rendered output. + +## Step 2: Set Up Your Project + +First, set up authentication with your Client ID and Client Secret: + +```csharp +// For complete examples and data files, please go to https://github.com/groupdocs-viewer-cloud/groupdocs-viewer-cloud-dotnet-samples +string MyClientSecret = ""; // Get your Client Secret from https://dashboard.groupdocs.cloud +string MyClientId = ""; // Get your Client ID from https://dashboard.groupdocs.cloud + +var configuration = new Configuration(MyClientId, MyClientSecret); +var apiInstance = new ViewApi(configuration); +``` + +## Step 3: Rendering a Presentation with Notes to HTML + +Let's start with a basic example of rendering a PowerPoint presentation with notes: + +```csharp +var viewOptions = new ViewOptions +{ + FileInfo = new FileInfo + { + FilePath = "with_notes.pptx" // Document in your cloud storage + }, + ViewFormat = ViewOptions.ViewFormatEnum.HTML, + + RenderOptions = new RenderOptions + { + RenderNotes = true // Enable notes rendering + } +}; + +var response = apiInstance.CreateView(new CreateViewRequest(viewOptions)); +``` + +## Step 4: Rendering Notes in PDF Output + +You can also include notes when converting presentations to PDF: + +```csharp +var viewOptions = new ViewOptions +{ + FileInfo = new FileInfo + { + FilePath = "with_notes.pptx" + }, + ViewFormat = ViewOptions.ViewFormatEnum.PDF, + + RenderOptions = new RenderOptions + { + RenderNotes = true + } +}; + +var response = apiInstance.CreateView(new CreateViewRequest(viewOptions)); +``` + +## Step 5: Rendering Notes in Image Output + +When rendering to image formats like JPG or PNG, you can still include the notes: + +```csharp +var viewOptions = new ViewOptions +{ + FileInfo = new FileInfo + { + FilePath = "with_notes.pptx" + }, + ViewFormat = ViewOptions.ViewFormatEnum.PNG, + + RenderOptions = new RenderOptions + { + RenderNotes = true + } +}; + +var response = apiInstance.CreateView(new CreateViewRequest(viewOptions)); +``` + +## Step 6: Combining Note Rendering with Other Options + +You can combine note rendering with other rendering options, such as watermarking: + +```csharp +var viewOptions = new ViewOptions +{ + FileInfo = new FileInfo + { + FilePath = "with_notes.pptx" + }, + ViewFormat = ViewOptions.ViewFormatEnum.HTML, + + RenderOptions = new RenderOptions + { + RenderNotes = true + }, + + Watermark = new Watermark + { + Text = "DRAFT", + Color = "#FF0000", + Position = Watermark.PositionEnum.Diagonal + } +}; + +var response = apiInstance.CreateView(new CreateViewRequest(viewOptions)); +``` + +## Try It Yourself + +Now it's your turn to experiment with note rendering: + +1. Try rendering the same presentation with and without notes to see the difference +2. Test with presentations that have extensive notes to see how they appear in the output +3. Compare how notes look in different output formats (HTML, PDF, images) +4. Implement a toggle in your application to let users show or hide notes + +## Common Issues and Troubleshooting + +Issue: Notes aren't appearing despite enabling RenderNotes +Solution: Ensure the presentation actually contains notes. Not all slides may have notes attached. + +Issue: Notes are appearing but the formatting looks different +Solution: Note formatting may be simplified in the rendered output compared to the original PowerPoint view. + +Issue: Notes are cut off or truncated in the rendered output +Solution: Long notes may be truncated in some formats. Consider adjusting page settings or using a format that better accommodates lengthy notes. + +## Complete Code Examples + +### cURL Example + +```bash +# First get JSON Web Token +curl -v "https://api.groupdocs.cloud/connect/token" \ +-X POST \ +-d "grant_type=client_credentials&client_id=xxxx&client_secret=xxxx" \ +-H "Content-Type: application/x-www-form-urlencoded" \ +-H "Accept: application/json" + +# Render presentation with notes +curl -v "https://api.groupdocs.cloud/v2.0/viewer/view" \ +-X POST \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +-H "Authorization: Bearer " \ +-d "{ + 'FileInfo': { + 'FilePath': 'with_notes.pptx' + }, + 'ViewFormat': 'HTML', + 'RenderOptions': { + 'RenderNotes': true + } +}" +``` + +### SDK Examples + +#### C# Example + +```csharp +// For complete examples and data files, please go to https://github.com/groupdocs-viewer-cloud/groupdocs-viewer-cloud-dotnet-samples +string MyClientSecret = ""; // Get Client Id and Client Secret from https://dashboard.groupdocs.cloud +string MyClientId = ""; // Get Client Id and Client Secret from https://dashboard.groupdocs.cloud + +var configuration = new Configuration(MyClientId, MyClientSecret); +var apiInstance = new ViewApi(configuration); + +var viewOptions = new ViewOptions +{ + FileInfo = new FileInfo + { + FilePath = "with_notes.pptx" + }, + ViewFormat = ViewOptions.ViewFormatEnum.HTML, + + RenderOptions = new RenderOptions + { + RenderNotes = true + } +}; + +var response = apiInstance.CreateView(new CreateViewRequest(viewOptions)); +``` + +#### Python Example + +```python +# For complete examples and data files, please go to https://github.com/groupdocs-viewer-cloud/groupdocs-viewer-cloud-python-samples +import groupdocs_viewer_cloud + +client_id = "XXXX-XXXX-XXXX-XXXX" # Get Client Id and Client Secret from https://dashboard.groupdocs.cloud +client_secret = "XXXXXXXXXXXXXXXX" # Get Client Id and Client Secret from https://dashboard.groupdocs.cloud + +apiInstance = groupdocs_viewer_cloud.ViewApi.from_keys(client_id, client_secret) + +view_options = groupdocs_viewer_cloud.ViewOptions() +view_options.file_info = groupdocs_viewer_cloud.FileInfo() +view_options.file_info.file_path = "with_notes.pptx" +view_options.view_format = "HTML" +view_options.render_options = groupdocs_viewer_cloud.HtmlOptions() +view_options.render_options.render_notes = True + +request = groupdocs_viewer_cloud.CreateViewRequest(view_options) +response = apiInstance.create_view(request) +``` + +#### Java Example + +```java +// For complete examples and data files, please go to https://github.com/groupdocs-viewer-cloud/groupdocs-viewer-cloud-java-samples +String MyClientSecret = ""; // Get Client Id and Client Secret from https://dashboard.groupdocs.cloud +String MyClientId = ""; // Get Client Id and Client Secret from https://dashboard.groupdocs.cloud + +Configuration configuration = new Configuration(MyClientId, MyClientSecret); +ViewApi apiInstance = new ViewApi(configuration); + +FileInfo fileInfo = new FileInfo(); +fileInfo.setFilePath("with_notes.pptx"); +ViewOptions viewOptions = new ViewOptions(); +viewOptions.setFileInfo(fileInfo); +viewOptions.setViewFormat(ViewFormatEnum.HTML); +RenderOptions renderOptions = new RenderOptions(); +renderOptions.setRenderNotes(true); +viewOptions.setRenderOptions(renderOptions); + +ViewResult response = apiInstance.createView(new CreateViewRequest(viewOptions)); +``` + +## What You've Learned + +In this tutorial, you've learned: + +- How to enable note rendering in presentations +- How to apply note rendering across different output formats +- Techniques for combining note rendering with other rendering options +- How to handle issues with note rendering in different scenarios + +## Further Practice + +To solidify your knowledge, try these exercises: + +1. Create a presentation viewer that toggles between showing and hiding notes +2. Build a system that extracts only the notes from presentations for review +3. Implement a feature that allows notes to be printed separately from slides +4. Develop a tool that compares presenter notes across multiple presentations + + +## Helpful Resources + +- [Product Page](https://products.groupdocs.cloud/viewer/) +- [Documentation](https://docs.groupdocs.cloud/viewer/) +- [Live Demo](https://products.groupdocs.app/viewer/family) +- [API Reference UI](https://reference.groupdocs.cloud/viewer/) +- [Blog](https://blog.groupdocs.cloud/categories/groupdocs.viewer-cloud-product-family/) +- [Free Support](https://forum.groupdocs.cloud/c/viewer/9) +- [Free Trial](https://dashboard.groupdocs.cloud/#/apps) + +## Feedback and Questions + +Did you find this tutorial helpful? Do you have questions about implementing note rendering in your application? Let us know in the [GroupDocs.Viewer Cloud forum](https://forum.groupdocs.cloud/c/viewer/9). diff --git a/content/viewer/english/advanced-usage/render-hidden-pages/_index.md b/content/viewer/english/advanced-usage/render-hidden-pages/_index.md new file mode 100644 index 0000000..b904d98 --- /dev/null +++ b/content/viewer/english/advanced-usage/render-hidden-pages/_index.md @@ -0,0 +1,301 @@ +--- +title: How to Render Hidden Pages in GroupDocs.Viewer Cloud Tutorial +url: /advanced-usage/render-hidden-pages/ +description: Learn how to render hidden pages, slides, and worksheets in documents using GroupDocs.Viewer Cloud API in this step-by-step tutorial for developers. +weight: 80 +--- + +## Tutorial: How to Render Hidden Pages + +In this tutorial, you'll learn how to reveal and render hidden content in documents using GroupDocs.Viewer Cloud API. Many document formats support hiding specific pages, slides, or worksheets that aren't visible during normal viewing but contain important information that you might need to access. + +## Learning Objectives + +By the end of this tutorial, you'll be able to: +- Enable rendering of hidden pages in various document formats +- Display hidden slides in presentations +- Reveal hidden worksheets in spreadsheets +- Access hidden layers in diagrams +- Apply these techniques across different output formats + +## Prerequisites + +Before you begin this tutorial, you need: + +1. A GroupDocs.Viewer Cloud account (if you don't have one, [sign up for a free trial](https://dashboard.groupdocs.cloud/#/apps)) +2. Your Client ID and Client Secret credentials from the GroupDocs Cloud Dashboard +3. Basic understanding of REST APIs +4. Development environment for your preferred language (C#, Java, Python, etc.) +5. [GroupDocs.Viewer Cloud SDK](https://github.com/groupdocs-viewer-cloud) installed for your language of choice + +## The Practical Scenario + +Imagine you're building a document audit system that needs to analyze all content within files, including hidden information. You need to ensure that hidden pages, slides, or worksheets are visible when rendering documents for comprehensive review, ensuring no information is overlooked during the audit process. + +## Step 1: Understanding Hidden Content in Documents + +Hidden content is available in several document types: +- Presentations: Hidden slides are not displayed during presentations but exist in the file +- Spreadsheets: Hidden worksheets are not visible in the workbook tab list +- Diagrams: Hidden layers contain content that's not visible in the default view + +By default, GroupDocs.Viewer Cloud does not render hidden content. However, you can enable this feature by setting the `RenderHiddenPages` property to `true` in your rendering options. + +## Step 2: Set Up Your Project + +First, set up authentication with your Client ID and Client Secret: + +```csharp +// For complete examples and data files, please go to https://github.com/groupdocs-viewer-cloud/groupdocs-viewer-cloud-dotnet-samples +string MyClientSecret = ""; // Get your Client Secret from https://dashboard.groupdocs.cloud +string MyClientId = ""; // Get your Client ID from https://dashboard.groupdocs.cloud + +var configuration = new Configuration(MyClientId, MyClientSecret); +var apiInstance = new ViewApi(configuration); +``` + +## Step 3: Rendering Hidden Slides in Presentations + +Let's start with a practical example of rendering hidden slides in a PowerPoint presentation: + +```csharp +var viewOptions = new ViewOptions +{ + FileInfo = new FileInfo + { + FilePath = "with_hidden_page.pptx" // Document in your cloud storage + }, + ViewFormat = ViewOptions.ViewFormatEnum.HTML, + + RenderOptions = new RenderOptions + { + RenderHiddenPages = true // Enable rendering of hidden slides + } +}; + +var response = apiInstance.CreateView(new CreateViewRequest(viewOptions)); +``` + +## Step 4: Revealing Hidden Worksheets in Spreadsheets + +Similar to presentations, you can reveal hidden worksheets in Excel files: + +```csharp +var viewOptions = new ViewOptions +{ + FileInfo = new FileInfo + { + FilePath = "spreadsheet_with_hidden_sheets.xlsx" + }, + ViewFormat = ViewOptions.ViewFormatEnum.HTML, + + RenderOptions = new RenderOptions + { + RenderHiddenPages = true // Show hidden worksheets + } +}; + +var response = apiInstance.CreateView(new CreateViewRequest(viewOptions)); +``` + +## Step 5: Displaying Hidden Content in Diagrams + +For diagram files with hidden layers or pages: + +```csharp +var viewOptions = new ViewOptions +{ + FileInfo = new FileInfo + { + FilePath = "diagram_with_hidden_layers.vsdx" + }, + ViewFormat = ViewOptions.ViewFormatEnum.HTML, + + RenderOptions = new RenderOptions + { + RenderHiddenPages = true // Reveal hidden content + } +}; + +var response = apiInstance.CreateView(new CreateViewRequest(viewOptions)); +``` + +## Step 6: Rendering Hidden Content to PDF + +The same approach works when converting to PDF format: + +```csharp +var viewOptions = new ViewOptions +{ + FileInfo = new FileInfo + { + FilePath = "with_hidden_page.pptx" + }, + ViewFormat = ViewOptions.ViewFormatEnum.PDF, + + RenderOptions = new RenderOptions + { + RenderHiddenPages = true + } +}; + +var response = apiInstance.CreateView(new CreateViewRequest(viewOptions)); +``` + +## Try It Yourself + +Now it's your turn to experiment with hidden content rendering: + +1. Try rendering the same document with and without the hidden pages to see the difference +2. Test different document types to understand how hidden content is handled in each format +3. Combine hidden content rendering with other options like watermarking or page selection +4. Build a feature that compares visible and hidden content in a document + +## Common Issues and Troubleshooting + +Issue: No additional pages appear when enabling RenderHiddenPages +Solution: The document might not contain any hidden pages. Not all documents have hidden content. + +Issue: Some content still remains hidden despite enabling RenderHiddenPages +Solution: Some content may be inaccessible due to document security settings or encryption. + +Issue: Different behavior across document formats +Solution: Each document format implements hiding differently. The way hidden content is revealed may vary between formats. + +## Complete Code Examples + +### cURL Example + +```bash +# First get JSON Web Token +curl -v "https://api.groupdocs.cloud/connect/token" \ +-X POST \ +-d "grant_type=client_credentials&client_id=xxxx&client_secret=xxxx" \ +-H "Content-Type: application/x-www-form-urlencoded" \ +-H "Accept: application/json" + +# Render document with hidden pages +curl -v "https://api.groupdocs.cloud/v2.0/viewer/view" \ +-X POST \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +-H "Authorization: Bearer " \ +-d "{ + 'FileInfo': { + 'FilePath': 'with_hidden_page.pptx' + }, + 'ViewFormat': 'HTML', + 'RenderOptions': { + 'RenderHiddenPages': true + } +}" +``` + +### SDK Examples + +#### C# Example + +```csharp +// For complete examples and data files, please go to https://github.com/groupdocs-viewer-cloud/groupdocs-viewer-cloud-dotnet-samples +string MyClientSecret = ""; // Get Client Id and Client Secret from https://dashboard.groupdocs.cloud +string MyClientId = ""; // Get Client Id and Client Secret from https://dashboard.groupdocs.cloud + +var configuration = new Configuration(MyClientId, MyClientSecret); +var apiInstance = new ViewApi(configuration); + +var viewOptions = new ViewOptions +{ + FileInfo = new FileInfo + { + FilePath = "with_hidden_page.pptx" + }, + ViewFormat = ViewOptions.ViewFormatEnum.HTML, + + RenderOptions = new RenderOptions + { + RenderHiddenPages = true + } +}; + +var response = apiInstance.CreateView(new CreateViewRequest(viewOptions)); +``` + +#### Python Example + +```python +# For complete examples and data files, please go to https://github.com/groupdocs-viewer-cloud/groupdocs-viewer-cloud-python-samples +import groupdocs_viewer_cloud + +client_id = "XXXX-XXXX-XXXX-XXXX" # Get Client Id and Client Secret from https://dashboard.groupdocs.cloud +client_secret = "XXXXXXXXXXXXXXXX" # Get Client Id and Client Secret from https://dashboard.groupdocs.cloud + +apiInstance = groupdocs_viewer_cloud.ViewApi.from_keys(client_id, client_secret) + +view_options = groupdocs_viewer_cloud.ViewOptions() +view_options.file_info = groupdocs_viewer_cloud.FileInfo() +view_options.file_info.file_path = "with_hidden_page.pptx" +view_options.view_format = "HTML" +view_options.render_options = groupdocs_viewer_cloud.HtmlOptions() +view_options.render_options.render_hidden_pages = True + +request = groupdocs_viewer_cloud.CreateViewRequest(view_options) +response = apiInstance.create_view(request) +``` + +#### Java Example + +```java +// For complete examples and data files, please go to https://github.com/groupdocs-viewer-cloud/groupdocs-viewer-cloud-java-samples +String MyClientSecret = ""; // Get Client Id and Client Secret from https://dashboard.groupdocs.cloud +String MyClientId = ""; // Get Client Id and Client Secret from https://dashboard.groupdocs.cloud + +Configuration configuration = new Configuration(MyClientId, MyClientSecret); +ViewApi apiInstance = new ViewApi(configuration); + +FileInfo fileInfo = new FileInfo(); +fileInfo.setFilePath("with_hidden_page.pptx"); +ViewOptions viewOptions = new ViewOptions(); +viewOptions.setFileInfo(fileInfo); +viewOptions.setViewFormat(ViewFormatEnum.HTML); +RenderOptions renderOptions = new RenderOptions(); +renderOptions.setRenderHiddenPages(true); +viewOptions.setRenderOptions(renderOptions); + +ViewResult response = apiInstance.createView(new CreateViewRequest(viewOptions)); +``` + +## What You've Learned + +In this tutorial, you've learned: + +- How to enable rendering of hidden content in documents +- Which document types support hidden content rendering +- How to configure hidden content display across different output formats +- Practical applications for accessing hidden content in documents + +## Further Practice + +To solidify your knowledge, try these exercises: + +1. Build a document inspector that shows all hidden content in a document +2. Create a system that compares visible and hidden content side by side +3. Implement a feature that highlights or marks content that was originally hidden +4. Develop a tool that extracts only the hidden content from documents + +## Next Tutorial + +Ready to learn more? Check out our tutorial on [Rendering Document Notes](/advanced-usage/render-document-with-notes/) to learn how to display presentation notes and other annotations. + +## Helpful Resources + +- [Product Page](https://products.groupdocs.cloud/viewer/) +- [Documentation](https://docs.groupdocs.cloud/viewer/) +- [Live Demo](https://products.groupdocs.app/viewer/family) +- [API Reference UI](https://reference.groupdocs.cloud/viewer/) +- [Blog](https://blog.groupdocs.cloud/categories/groupdocs.viewer-cloud-product-family/) +- [Free Support](https://forum.groupdocs.cloud/c/viewer/9) +- [Free Trial](https://dashboard.groupdocs.cloud/#/apps) + +## Feedback and Questions + +Did you find this tutorial helpful? Do you have questions about implementing hidden content rendering in your application? Let us know in the [GroupDocs.Viewer Cloud forum](https://forum.groupdocs.cloud/c/viewer/9). \ No newline at end of file diff --git a/content/viewer/english/advanced-usage/render-with-custom-fonts/_index.md b/content/viewer/english/advanced-usage/render-with-custom-fonts/_index.md new file mode 100644 index 0000000..50e3fe7 --- /dev/null +++ b/content/viewer/english/advanced-usage/render-with-custom-fonts/_index.md @@ -0,0 +1,299 @@ +--- +title: How to Render Documents with Custom Fonts in GroupDocs.Viewer Cloud Tutorial +description: Learn how to render documents with custom fonts using GroupDocs.Viewer Cloud API in this step-by-step tutorial for developers. +url: /advanced-usage/render-with-custom-fonts/ +weight: 100 +--- + +## Tutorial: How to Render Documents with Custom Fonts + +In this tutorial, you'll learn how to render documents with custom fonts using GroupDocs.Viewer Cloud API. Font consistency is crucial for maintaining the visual integrity of documents, especially when working with documents that use specialized or brand-specific fonts. + +## Learning Objectives + +By the end of this tutorial, you'll be able to: +- Configure custom font sources for document rendering +- Ensure consistent visual appearance across different platforms +- Handle missing font scenarios effectively +- Apply custom font rendering across various document formats + +## Prerequisites + +Before you begin this tutorial, you need: + +1. A GroupDocs.Viewer Cloud account (if you don't have one, [sign up for a free trial](https://dashboard.groupdocs.cloud/#/apps)) +2. Your Client ID and Client Secret credentials from the GroupDocs Cloud Dashboard +3. Basic understanding of REST APIs +4. Development environment for your preferred language (C#, Java, Python, etc.) +5. [GroupDocs.Viewer Cloud SDK](https://github.com/groupdocs-viewer-cloud) installed for your language of choice +6. Custom font files that you want to use (if any) + +## The Practical Scenario + +Imagine you're developing a corporate document management system for a company with a strict brand identity. The company uses custom fonts in all their documents, and it's essential that these fonts render correctly when viewed through your application. Without proper font handling, documents would appear with substituted fonts, potentially breaking layouts and diminishing the professional appearance. + +## Step 1: Understanding Custom Font Handling + +When rendering documents, GroupDocs.Viewer Cloud needs access to all fonts used in those documents. If a document uses fonts that aren't available, the API will substitute them with standard fonts, which can affect the document's appearance. + +To solve this problem, GroupDocs.Viewer Cloud provides the `FontsPath` property, which allows you to specify a folder in your cloud storage containing custom fonts. When rendering documents, the API will check this folder for any required fonts. + +## Step 2: Set Up Your Project + +First, set up authentication with your Client ID and Client Secret: + +```csharp +// For complete examples and data files, please go to https://github.com/groupdocs-viewer-cloud/groupdocs-viewer-cloud-dotnet-samples +string MyClientSecret = ""; // Get your Client Secret from https://dashboard.groupdocs.cloud +string MyClientId = ""; // Get your Client ID from https://dashboard.groupdocs.cloud + +var configuration = new Configuration(MyClientId, MyClientSecret); +var apiInstance = new ViewApi(configuration); +``` + +## Step 3: Upload Custom Fonts to Cloud Storage + +Before rendering documents with custom fonts, you need to upload those fonts to your cloud storage. You can do this using the Storage API: + +```csharp +// Example to upload fonts to cloud storage +string fontsFolderPath = "Fonts"; // Path in cloud storage where fonts will be stored +string localFontPath = "BrandFont.ttf"; // Path to local font file + +// Create fonts folder if it doesn't exist +var folderApi = new FolderApi(configuration); +if (!folderApi.Exists(new ObjectExistsRequest(fontsFolderPath)).Exists) +{ + folderApi.CreateFolder(new CreateFolderRequest(fontsFolderPath)); +} + +// Upload font file +var fileApi = new FileApi(configuration); +using (var stream = File.Open(localFontPath, FileMode.Open)) +{ + var uploadRequest = new UploadFileRequest(fontsFolderPath + "/" + Path.GetFileName(localFontPath), stream); + fileApi.UploadFile(uploadRequest); +} +``` + +## Step 4: Rendering a Document with Custom Fonts + +Now that your fonts are in cloud storage, you can render documents using them: + +```csharp +var viewOptions = new ViewOptions +{ + FileInfo = new FileInfo + { + FilePath = "with_missing_font.odg" // Document in your cloud storage + }, + ViewFormat = ViewOptions.ViewFormatEnum.HTML, + + // Specify the folder containing custom fonts + FontsPath = "Fonts" +}; + +var response = apiInstance.CreateView(new CreateViewRequest(viewOptions)); +``` + +## Step 5: Handling Missing Fonts with Default Font + +In some cases, you might want to specify a default font to use when a specific font is missing. You can combine the `FontsPath` property with the `DefaultFontName` property: + +```csharp +var viewOptions = new ViewOptions +{ + FileInfo = new FileInfo + { + FilePath = "with_missing_font.odg" + }, + ViewFormat = ViewOptions.ViewFormatEnum.HTML, + + // Specify the folder containing custom fonts + FontsPath = "Fonts", + + RenderOptions = new RenderOptions + { + DefaultFontName = "Arial" // Fallback font if specific font is still missing + } +}; + +var response = apiInstance.CreateView(new CreateViewRequest(viewOptions)); +``` + +## Step 6: Using Custom Fonts in PDF Output + +The same approach works when converting to PDF format: + +```csharp +var viewOptions = new ViewOptions +{ + FileInfo = new FileInfo + { + FilePath = "with_missing_font.odg" + }, + ViewFormat = ViewOptions.ViewFormatEnum.PDF, + + // Specify the folder containing custom fonts + FontsPath = "Fonts" +}; + +var response = apiInstance.CreateView(new CreateViewRequest(viewOptions)); +``` + +## Try It Yourself + +Now it's your turn to experiment with custom font rendering: + +1. Upload some custom fonts to your cloud storage +2. Render documents with and without the FontsPath setting to see the difference +3. Try different combinations of font substitution strategies +4. Test with documents that use a variety of fonts + +## Common Issues and Troubleshooting + +Issue: Fonts still appear substituted despite specifying FontsPath +Solution: Ensure the font file names exactly match what's referenced in the document. Font matching is case-sensitive. + +Issue: Only some characters appear with the correct font +Solution: The font might not contain all the required glyphs. Ensure your font files are complete. + +Issue: Performance degradation with many font files +Solution: Only include the fonts you need in your fonts folder. Too many fonts can slow down rendering. + +Issue: Font files not found when rendering +Solution: Double-check that the fonts were successfully uploaded to the specified path in cloud storage. + +## Complete Code Examples + +### cURL Example + +```bash +# First get JSON Web Token +curl -v "https://api.groupdocs.cloud/connect/token" \ +-X POST \ +-d "grant_type=client_credentials&client_id=xxxx&client_secret=xxxx" \ +-H "Content-Type: application/x-www-form-urlencoded" \ +-H "Accept: application/json" + +# Render document with custom fonts +curl -v "https://api.groupdocs.cloud/v2.0/viewer/view" \ +-X POST \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +-H "Authorization: Bearer " \ +-d "{ + 'FileInfo': { + 'FilePath': 'with_missing_font.odg' + }, + 'ViewFormat': 'HTML', + 'FontsPath': 'Fonts' +}" +``` + +### SDK Examples + +#### C# Example + +```csharp +// For complete examples and data files, please go to https://github.com/groupdocs-viewer-cloud/groupdocs-viewer-cloud-dotnet-samples +string MyClientSecret = ""; // Get Client Id and Client Secret from https://dashboard.groupdocs.cloud +string MyClientId = ""; // Get Client Id and Client Secret from https://dashboard.groupdocs.cloud + +var configuration = new Configuration(MyClientId, MyClientSecret); +var apiInstance = new ViewApi(configuration); + +var viewOptions = new ViewOptions +{ + FileInfo = new FileInfo + { + FilePath = "with_missing_font.odg" + }, + ViewFormat = ViewOptions.ViewFormatEnum.HTML, + + // NOTE: Upload fonts to the folder using storage API before rendering + FontsPath = "Fonts" +}; + +var response = apiInstance.CreateView(new CreateViewRequest(viewOptions)); +``` + +#### Python Example + +```python +# For complete examples and data files, please go to https://github.com/groupdocs-viewer-cloud/groupdocs-viewer-cloud-python-samples +import groupdocs_viewer_cloud + +client_id = "XXXX-XXXX-XXXX-XXXX" # Get Client Id and Client Secret from https://dashboard.groupdocs.cloud +client_secret = "XXXXXXXXXXXXXXXX" # Get Client Id and Client Secret from https://dashboard.groupdocs.cloud + +apiInstance = groupdocs_viewer_cloud.ViewApi.from_keys(client_id, client_secret) + +view_options = groupdocs_viewer_cloud.ViewOptions() +view_options.file_info = groupdocs_viewer_cloud.FileInfo() +view_options.file_info.file_path = "with_missing_font.odg" +view_options.view_format = "HTML" +# NOTE: Upload fonts to the folder using storage API before rendering +view_options.fonts_path = "Fonts" + +request = groupdocs_viewer_cloud.CreateViewRequest(view_options) +response = apiInstance.create_view(request) +``` + +#### Java Example + +```java +// For complete examples and data files, please go to https://github.com/groupdocs-viewer-cloud/groupdocs-viewer-cloud-java-samples +String MyClientSecret = ""; // Get Client Id and Client Secret from https://dashboard.groupdocs.cloud +String MyClientId = ""; // Get Client Id and Client Secret from https://dashboard.groupdocs.cloud + +Configuration configuration = new Configuration(MyClientId, MyClientSecret); +ViewApi apiInstance = new ViewApi(configuration); + +FileInfo fileInfo = new FileInfo(); +fileInfo.setFilePath("with_missing_font.odg"); +ViewOptions viewOptions = new ViewOptions(); +viewOptions.setFileInfo(fileInfo); +viewOptions.setViewFormat(ViewFormatEnum.HTML); + +// NOTE: Upload fonts to the folder using storage API before rendering +viewOptions.setFontsPath("Fonts"); + +ViewResult response = apiInstance.createView(new CreateViewRequest(viewOptions)); +``` + +## What You've Learned + +In this tutorial, you've learned: + +- How to configure custom font sources for document rendering +- How to upload custom fonts to cloud storage +- How to specify default fonts for handling missing font scenarios +- How to apply custom font rendering across different output formats + +## Further Practice + +To solidify your knowledge, try these exercises: + +1. Build a font management system that allows uploading and managing custom fonts +2. Create a preview feature that shows how a document will look with different fonts +3. Implement a font detection system that identifies missing fonts in documents +4. Develop a solution that automatically downloads required fonts from a repository + +## Next Tutorial + +Ready to explore more advanced rendering options? Check out our document-specific rendering tutorials, starting with [PDF Document Rendering](/advanced-usage/rendering-pdf-documents/) to learn specialized techniques for different document formats. + +## Helpful Resources + +- [Product Page](https://products.groupdocs.cloud/viewer/) +- [Documentation](https://docs.groupdocs.cloud/viewer/) +- [Live Demo](https://products.groupdocs.app/viewer/family) +- [API Reference UI](https://reference.groupdocs.cloud/viewer/) +- [Blog](https://blog.groupdocs.cloud/categories/groupdocs.viewer-cloud-product-family/) +- [Free Support](https://forum.groupdocs.cloud/c/viewer/9) +- [Free Trial](https://dashboard.groupdocs.cloud/#/apps) + +## Feedback and Questions + +Did you find this tutorial helpful? Do you have questions about implementing custom font rendering in your application? Let us know in the [GroupDocs.Viewer Cloud forum](https://forum.groupdocs.cloud/c/viewer/9). \ No newline at end of file diff --git a/content/viewer/english/advanced-usage/rendering-outlook-files/_index.md b/content/viewer/english/advanced-usage/rendering-outlook-files/_index.md new file mode 100644 index 0000000..42d09a4 --- /dev/null +++ b/content/viewer/english/advanced-usage/rendering-outlook-files/_index.md @@ -0,0 +1,332 @@ +--- +title: How to Render Outlook Data Files with GroupDocs.Viewer Cloud API Tutorial +description: Learn how to render Outlook data files (PST, OST) with filtering and folder navigation in this comprehensive step-by-step tutorial +url: /advanced-usage/rendering-outlook-files/ +weight: 40 +--- + +# Tutorial: How to Render Outlook Data Files with GroupDocs.Viewer Cloud API + +## Learning Objectives + +In this tutorial, you'll learn how to render Outlook data files (PST, OST) with advanced options using GroupDocs.Viewer Cloud API. By the end of this tutorial, you'll be able to: + +- Render specific folders within Outlook data files +- Filter messages by content and sender/recipient +- Limit the number of items rendered from large mailboxes +- Retrieve information about Outlook data file structure +- Process email attachments + +## Prerequisites + +Before starting this tutorial, you should have: + +1. A GroupDocs.Viewer Cloud account (or [sign up for a free trial](https://dashboard.groupdocs.cloud/#/apps)) +2. Your Client ID and Client Secret credentials +3. Sample Outlook data files (PST or OST) to test with +4. Basic understanding of REST API concepts +5. Familiarity with your preferred programming language (C#, Java, Python, etc.) + +## Use Case Scenario + +Imagine you're developing an email archiving application that needs to provide access to historical email data stored in Outlook PST files. Users need to search through specific folders, filter messages by sender or content, and view only relevant emails without loading the entire mailbox. Your application needs to efficiently render this content while allowing for targeted navigation. + +## Tutorial Steps + +### 1. Rendering Specific Folders + +Outlook data files are organized into folders (Inbox, Sent Items, etc.). Rather than rendering the entire mailbox, you can specify which folder to render. + +#### Try it yourself + +```bash +# First get JSON Web Token +curl -v "https://api.groupdocs.cloud/connect/token" \ +-X POST \ +-d "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET" \ +-H "Content-Type: application/x-www-form-urlencoded" \ +-H "Accept: application/json" + +# Now render a specific folder (Inbox) from the Outlook data file +curl -v "https://api.groupdocs.cloud/v2.0/viewer/view" \ +-X POST \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +-H "Authorization: Bearer YOUR_JWT_TOKEN" \ +-d "{ + 'FileInfo': { + 'FilePath': 'SampleFiles/sample.ost' + }, + 'ViewFormat': 'HTML', + 'RenderOptions': { + 'OutlookOptions': { + 'Folder': 'Inbox' + } + } +}" +``` + +#### What you should see + +After executing the API call, you'll receive a JSON response with links to the rendered HTML pages and any attachments. The rendered content will only include messages from the Inbox folder of the Outlook data file. + +#### Navigating Nested Folders + +For nested folders, use the following naming convention: `{Parent folder name}\\{Sub folder name}` + +For example, to render a subfolder named "Important" within the Inbox: + +```bash +curl -v "https://api.groupdocs.cloud/v2.0/viewer/view" \ +-X POST \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +-H "Authorization: Bearer YOUR_JWT_TOKEN" \ +-d "{ + 'FileInfo': { + 'FilePath': 'SampleFiles/sample.ost' + }, + 'ViewFormat': 'HTML', + 'RenderOptions': { + 'OutlookOptions': { + 'Folder': 'Inbox\\Important' + } + } +}" +``` + +### 2. Filtering Messages + +When working with large mailboxes, you can filter messages by text content or by sender/recipient email addresses. + +#### Filtering by Text Content + +```bash +curl -v "https://api.groupdocs.cloud/v2.0/viewer/view" \ +-X POST \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +-H "Authorization: Bearer YOUR_JWT_TOKEN" \ +-d "{ + 'FileInfo': { + 'FilePath': 'SampleFiles/sample.ost' + }, + 'ViewFormat': 'HTML', + 'RenderOptions': { + 'OutlookOptions': { + 'TextFilter': 'Microsoft' + } + } +}" +``` + +This will render only messages containing the word "Microsoft" in their subject or body. + +#### Filtering by Sender/Recipient + +```bash +curl -v "https://api.groupdocs.cloud/v2.0/viewer/view" \ +-X POST \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +-H "Authorization: Bearer YOUR_JWT_TOKEN" \ +-d "{ + 'FileInfo': { + 'FilePath': 'SampleFiles/sample.ost' + }, + 'ViewFormat': 'HTML', + 'RenderOptions': { + 'OutlookOptions': { + 'AddressFilter': 'susan' + } + } +}" +``` + +This will render only messages where the sender or recipient email address contains "susan". + +#### Combining Filters + +You can combine both filters to narrow down your search: + +```bash +curl -v "https://api.groupdocs.cloud/v2.0/viewer/view" \ +-X POST \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +-H "Authorization: Bearer YOUR_JWT_TOKEN" \ +-d "{ + 'FileInfo': { + 'FilePath': 'SampleFiles/sample.ost' + }, + 'ViewFormat': 'HTML', + 'RenderOptions': { + 'OutlookOptions': { + 'TextFilter': 'Microsoft', + 'AddressFilter': 'susan' + } + } +}" +``` + +### 3. Limiting the Number of Items + +For very large mailboxes, you can limit the number of messages rendered from each folder to improve performance. + +#### Try it yourself + +```bash +curl -v "https://api.groupdocs.cloud/v2.0/viewer/view" \ +-X POST \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +-H "Authorization: Bearer YOUR_JWT_TOKEN" \ +-d "{ + 'FileInfo': { + 'FilePath': 'SampleFiles/sample.ost' + }, + 'ViewFormat': 'HTML', + 'RenderOptions': { + 'OutlookOptions': { + 'MaxItemsInFolder': 100 + } + } +}" +``` + +This will render at most 100 messages per folder, starting with the most recent. + +#### Learning checkpoint + +What would happen if you combine folder specification, filtering, and item limiting? Try creating an API call that: +1. Renders only the Inbox folder +2. Shows only messages containing the word "Report" +3. Limits the results to 50 items + +### 4. Getting Outlook Data File Information + +Before rendering, you might want to explore the structure of the Outlook data file to understand what folders are available. + +```bash +curl -v "https://api.groupdocs.cloud/v2.0/viewer/info" \ +-X POST \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +-H "Authorization: Bearer YOUR_JWT_TOKEN" \ +-d "{ + 'FileInfo': { + 'FilePath': 'SampleFiles/sample.ost' + } +}" +``` + +This will return information about the Outlook data file, including a list of all folders. + +#### Troubleshooting Tip + +If you're not seeing the expected folders or messages in your rendered output, use the info endpoint to verify the folder structure of your Outlook data file. The folder names in your rendering request must exactly match the actual folder names in the file. + +### 5. Handling Attachments + +When rendering Outlook data files, any email attachments are automatically included in the response. You can download these attachments using the provided URLs. + +## SDK Examples + +### C# Example + +```csharp +// For complete examples, see: https://github.com/groupdocs-viewer-cloud/groupdocs-viewer-cloud-dotnet-samples +string MyClientSecret = "YOUR_CLIENT_SECRET"; +string MyClientId = "YOUR_CLIENT_ID"; + +var configuration = new Configuration(MyClientId, MyClientSecret); +var apiInstance = new ViewApi(configuration); + +// Example: Render Inbox folder and filter messages +var viewOptions = new ViewOptions +{ + FileInfo = new FileInfo + { + FilePath = "SampleFiles/sample.ost" + }, + ViewFormat = ViewOptions.ViewFormatEnum.HTML, + RenderOptions = new HtmlOptions + { + OutlookOptions = new OutlookOptions + { + Folder = "Inbox", + TextFilter = "Report", + MaxItemsInFolder = 50 + } + } +}; + +var response = apiInstance.CreateView(new CreateViewRequest(viewOptions)); + +// Handle attachments if needed +foreach (var attachment in response.Attachments) +{ + Console.WriteLine($"Attachment: {attachment.Name}, URL: {attachment.DownloadUrl}"); +} +``` + +### Python Example + +```python +# For complete examples, see: https://github.com/groupdocs-viewer-cloud/groupdocs-viewer-cloud-python-samples +import groupdocs_viewer_cloud + +client_id = "YOUR_CLIENT_ID" +client_secret = "YOUR_CLIENT_SECRET" + +apiInstance = groupdocs_viewer_cloud.ViewApi.from_keys(client_id, client_secret) + +# Example: Get information about the Outlook data file +view_options = groupdocs_viewer_cloud.ViewOptions() +view_options.file_info = groupdocs_viewer_cloud.FileInfo() +view_options.file_info.file_path = "SampleFiles/sample.ost" + +# First get information about the file +info_request = groupdocs_viewer_cloud.GetInfoRequest(view_options) +info_response = apiInstance.get_info(info_request) + +# Print available folders +print("Available folders:") +for folder in info_response.outlook_view_info.folders: + print(f" - {folder}") + +# Now render a specific folder with filtering +view_options.view_format = "HTML" +view_options.render_options = groupdocs_viewer_cloud.HtmlOptions() +view_options.render_options.outlook_options = groupdocs_viewer_cloud.OutlookOptions() +view_options.render_options.outlook_options.folder = "Inbox" +view_options.render_options.outlook_options.address_filter = "susan" + +request = groupdocs_viewer_cloud.CreateViewRequest(view_options) +response = apiInstance.create_view(request) +``` + +## What You've Learned + +In this tutorial, you've learned how to: +- Render specific folders within Outlook data files +- Filter messages by content and sender/recipient +- Limit the number of items rendered for better performance +- Retrieve structural information about Outlook data files +- Access and process email attachments + +## Further Practice + +Try creating a workflow that first gets information about the Outlook data file structure, then renders specific folders based on user selection, and finally allows filtering within those folders. This simulates a real-world email navigation system. + +## Helpful Resources + +- [Product Page](https://products.groupdocs.cloud/viewer/) +- [Documentation](https://docs.groupdocs.cloud/viewer/) +- [API Reference UI](https://reference.groupdocs.cloud/viewer/) +- [Free Support Forum](https://forum.groupdocs.cloud/c/viewer/9) +- [Free Trial](https://dashboard.groupdocs.cloud/#/apps) + +## Feedback and Questions + +If you have questions about this tutorial or any aspect of using GroupDocs.Viewer Cloud API, please visit our [support forum](https://forum.groupdocs.cloud/c/viewer/9). diff --git a/content/viewer/english/advanced-usage/rendering-pdf-documents/_index.md b/content/viewer/english/advanced-usage/rendering-pdf-documents/_index.md new file mode 100644 index 0000000..e29e4a8 --- /dev/null +++ b/content/viewer/english/advanced-usage/rendering-pdf-documents/_index.md @@ -0,0 +1,287 @@ +--- +title: How to Render PDF Documents with GroupDocs.Viewer Cloud API Tutorial +url: /advanced-usage/rendering-pdf-documents/ +description: Learn step-by-step how to render PDF documents with advanced options using GroupDocs.Viewer Cloud API in this comprehensive tutorial +weight: 50 +--- + +# Tutorial: How to Render PDF Documents with GroupDocs.Viewer Cloud API + +## Learning Objectives + +In this tutorial, you'll learn how to render PDF documents with advanced options using GroupDocs.Viewer Cloud API. By the end of this tutorial, you'll be able to: + +- Adjust image quality in PDF documents for optimal rendering +- Enable font hinting to improve text display +- Implement layered rendering for multi-layered PDFs +- Disable character grouping for improved content positioning +- Render pages at their original size + +## Prerequisites + +Before starting this tutorial, you should have: + +1. A GroupDocs.Viewer Cloud account (or [sign up for a free trial](https://dashboard.groupdocs.cloud/#/apps)) +2. Your Client ID and Client Secret credentials +3. A sample PDF document to test with +4. Basic understanding of REST API concepts +5. Familiarity with your preferred programming language (C#, Java, Python, etc.) + +## Use Case Scenario + +Let's imagine you're developing a document management system where users need to view PDF documents with various quality levels depending on their internet connection speed. You'll need to implement options to adjust rendering quality, enable font hinting for better text display, and handle multi-layered PDFs correctly. + +## Tutorial Steps + +### 1. Adjusting Image Quality + +When rendering PDF documents to HTML, you can adjust the quality of embedded images to balance between performance and visual quality. GroupDocs.Viewer Cloud API provides three quality levels: + +- Low: Fast performance with smaller file size but lower image quality +- Medium: Balanced performance and quality +- High: Best quality but slower performance and larger file size + +#### Try it yourself + +```bash +# First get JSON Web Token +curl -v "https://api.groupdocs.cloud/connect/token" \ +-X POST \ +-d "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET" \ +-H "Content-Type: application/x-www-form-urlencoded" \ +-H "Accept: application/json" + +# Now render the PDF with Medium image quality +curl -v "https://api.groupdocs.cloud/v2.0/viewer/view" \ +-X POST \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +-H "Authorization: Bearer YOUR_JWT_TOKEN" \ +-d "{ + 'FileInfo': { + 'FilePath': 'SampleFiles/sample.pdf' + }, + 'ViewFormat': 'HTML', + 'RenderOptions': { + 'PdfDocumentOptions': { + 'ImageQuality': 'Medium' + } + } +}" +``` + +#### What you should see + +After executing the API call, you'll receive a JSON response with links to the rendered HTML pages. The embedded images in these pages will be rendered with medium quality, providing a good balance between visual quality and file size. + +#### Learning checkpoint +What happens if you change the `ImageQuality` from `Medium` to `High`? Try it and observe the difference in the rendered output and file size. + +### 2. Enabling Font Hinting + +Font hinting adjusts the display of outline fonts to improve readability at different sizes and resolutions. This is especially useful when rendering PDFs to image formats like PNG or JPG. + +#### Try it yourself + +```bash +# Render PDF with font hinting enabled +curl -v "https://api.groupdocs.cloud/v2.0/viewer/view" \ +-X POST \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +-H "Authorization: Bearer YOUR_JWT_TOKEN" \ +-d "{ + 'FileInfo': { + 'FilePath': 'SampleFiles/sample.pdf' + }, + 'ViewFormat': 'PNG', + 'RenderOptions': { + 'PdfDocumentOptions': { + 'EnableFontHinting': true + } + } +}" +``` + +#### What you should see + +The rendered PNG images will have improved text display, particularly for smaller font sizes, as the font hinting feature adjusts character outlines for better readability. + +### 3. Enabling Layered Rendering + +Multi-layered PDF documents can have complex layouts with text and graphics arranged in different layers. By enabling layered rendering, GroupDocs.Viewer Cloud renders text and graphics according to their z-order in the original PDF document. + +#### Try it yourself + +```bash +# Render PDF with layered rendering enabled +curl -v "https://api.groupdocs.cloud/v2.0/viewer/view" \ +-X POST \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +-H "Authorization: Bearer YOUR_JWT_TOKEN" \ +-d "{ + 'FileInfo': { + 'FilePath': 'SampleFiles/sample.pdf' + }, + 'ViewFormat': 'HTML', + 'RenderOptions': { + 'PdfDocumentOptions': { + 'EnableLayeredRendering': true + } + } +}" +``` + +#### Troubleshooting Tip + +If you notice overlapping text or misaligned graphics in your rendered PDF, enabling layered rendering often resolves these issues. This option is only supported when rendering to HTML format. + +### 4. Disabling Characters Grouping + +To improve content positioning when rendering PDFs, especially those with complex layouts, you can disable character grouping: + +```bash +curl -v "https://api.groupdocs.cloud/v2.0/viewer/view" \ +-X POST \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +-H "Authorization: Bearer YOUR_JWT_TOKEN" \ +-d "{ + 'FileInfo': { + 'FilePath': 'SampleFiles/sample.pdf' + }, + 'ViewFormat': 'HTML', + 'RenderOptions': { + 'PdfDocumentOptions': { + 'DisableCharsGrouping': true + } + } +}" +``` + +### 5. Rendering at Original Page Size + +When rendering to image formats, you can maintain the exact dimensions of the original PDF pages: + +```bash +curl -v "https://api.groupdocs.cloud/v2.0/viewer/view" \ +-X POST \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +-H "Authorization: Bearer YOUR_JWT_TOKEN" \ +-d "{ + 'FileInfo': { + 'FilePath': 'SampleFiles/sample.pdf' + }, + 'ViewFormat': 'PNG', + 'RenderOptions': { + 'PdfDocumentOptions': { + 'RenderOriginalPageSize': true + } + } +}" +``` + +### 6. Getting PDF Document Information + +Before rendering, you may want to get information about the PDF document: + +```bash +curl -v "https://api.groupdocs.cloud/v2.0/viewer/info" \ +-X POST \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +-H "Authorization: Bearer YOUR_JWT_TOKEN" \ +-d "{ + 'FileInfo': { + 'FilePath': 'SampleFiles/sample.pdf' + } +}" +``` + +## SDK Examples + +### C# Example + +```csharp +// For complete examples, see: https://github.com/groupdocs-viewer-cloud/groupdocs-viewer-cloud-dotnet-samples +string MyClientSecret = "YOUR_CLIENT_SECRET"; +string MyClientId = "YOUR_CLIENT_ID"; + +var configuration = new Configuration(MyClientId, MyClientSecret); +var apiInstance = new ViewApi(configuration); + +// Example: Adjust image quality when rendering PDF to HTML +var viewOptions = new ViewOptions +{ + FileInfo = new FileInfo + { + FilePath = "SampleFiles/sample.pdf" + }, + ViewFormat = ViewOptions.ViewFormatEnum.HTML, + RenderOptions = new HtmlOptions + { + PdfDocumentOptions = new PdfDocumentOptions + { + ImageQuality = PdfDocumentOptions.ImageQualityEnum.Medium + } + } +}; + +var response = apiInstance.CreateView(new CreateViewRequest(viewOptions)); +``` + +### Python Example + +```python +# For complete examples, see: https://github.com/groupdocs-viewer-cloud/groupdocs-viewer-cloud-python-samples +import groupdocs_viewer_cloud + +client_id = "YOUR_CLIENT_ID" +client_secret = "YOUR_CLIENT_SECRET" + +apiInstance = groupdocs_viewer_cloud.ViewApi.from_keys(client_id, client_secret) + +# Example: Enable font hinting when rendering to PNG +view_options = groupdocs_viewer_cloud.ViewOptions() +view_options.file_info = groupdocs_viewer_cloud.FileInfo() +view_options.file_info.file_path = "SampleFiles/sample.pdf" +view_options.view_format = "PNG" +view_options.render_options = groupdocs_viewer_cloud.ImageOptions() +view_options.render_options.pdf_document_options = groupdocs_viewer_cloud.PdfDocumentOptions() +view_options.render_options.pdf_document_options.enable_font_hinting = True + +request = groupdocs_viewer_cloud.CreateViewRequest(view_options) +response = apiInstance.create_view(request) +``` + +## What You've Learned + +In this tutorial, you've learned how to: +- Adjust image quality in PDF documents for optimal rendering +- Enable font hinting to improve text display in rendered images +- Implement layered rendering for complex multi-layered PDFs +- Disable character grouping for better content positioning +- Render pages at their original size +- Retrieve PDF document information before rendering + +## Further Practice + +Try combining multiple PDF rendering options in a single request to see how they interact. For example, enable both layered rendering and disable character grouping to see how they work together for complex PDF layouts. + +## Next Tutorial + +Continue your learning journey with our [Tutorial on Rendering Spreadsheets](/advanced-usage/rendering-spreadsheets/), where you'll discover techniques for handling Excel and other spreadsheet formats with GroupDocs.Viewer Cloud API. + +## Helpful Resources + +- [Product Page](https://products.groupdocs.cloud/viewer/) +- [Documentation](https://docs.groupdocs.cloud/viewer/) +- [API Reference UI](https://reference.groupdocs.cloud/viewer/) +- [Free Support Forum](https://forum.groupdocs.cloud/c/viewer/9) +- [Free Trial](https://dashboard.groupdocs.cloud/#/apps) + +## Feedback and Questions + +If you have questions about this tutorial or any aspect of using GroupDocs.Viewer Cloud API, please visit our [support forum](https://forum.groupdocs.cloud/c/viewer/9). diff --git a/content/viewer/english/advanced-usage/rendering-spreadsheets/_index.md b/content/viewer/english/advanced-usage/rendering-spreadsheets/_index.md new file mode 100644 index 0000000..a88f623 --- /dev/null +++ b/content/viewer/english/advanced-usage/rendering-spreadsheets/_index.md @@ -0,0 +1,330 @@ +--- +title: How to Render Spreadsheets with GroupDocs.Viewer Cloud API Tutorial +url: /advanced-usage/rendering-spreadsheets/ +description: Learn how to render Excel and other spreadsheet formats with advanced options like grid lines, hidden rows, and text overflow in this step-by-step tutorial +weight: 120 +--- + +# Tutorial: How to Render Spreadsheets with GroupDocs.Viewer Cloud API + +## Learning Objectives + +In this tutorial, you'll learn how to render Excel and other spreadsheet formats with advanced options using GroupDocs.Viewer Cloud API. By the end of this tutorial, you'll be able to: + +- Render grid lines in spreadsheets +- Control the visibility of hidden rows and columns +- Manage text overflow in cells +- Skip rendering empty rows and columns +- Split worksheets into pages +- Render print areas only + +## Prerequisites + +Before starting this tutorial, you should have: + +1. A GroupDocs.Viewer Cloud account (or [sign up for a free trial](https://dashboard.groupdocs.cloud/#/apps)) +2. Your Client ID and Client Secret credentials +3. Sample spreadsheet files (Excel, CSV, etc.) to test with +4. Basic understanding of REST API concepts +5. Familiarity with your preferred programming language (C#, Java, Python, etc.) + +## Use Case Scenario + +Imagine you're building a financial reporting application where users need to view spreadsheets with various formatting options. Some users want to see grid lines for better readability, while others need to view hidden data for auditing purposes. Additionally, you need to handle large spreadsheets efficiently by paginating them and skipping empty content. + +## Tutorial Steps + +### 1. Rendering Grid Lines + +By default, GroupDocs.Viewer Cloud doesn't render grid lines in spreadsheets. Enable them to improve readability and visual structure. + +#### Try it yourself + +```bash +# First get JSON Web Token +curl -v "https://api.groupdocs.cloud/connect/token" \ +-X POST \ +-d "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET" \ +-H "Content-Type: application/x-www-form-urlencoded" \ +-H "Accept: application/json" + +# Now render the spreadsheet with grid lines +curl -v "https://api.groupdocs.cloud/v2.0/viewer/view" \ +-X POST \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +-H "Authorization: Bearer YOUR_JWT_TOKEN" \ +-d "{ + 'FileInfo': { + 'FilePath': 'SampleFiles/sample.xlsx' + }, + 'ViewFormat': 'HTML', + 'RenderOptions': { + 'SpreadsheetOptions': { + 'RenderGridLines': true + } + } +}" +``` + +#### What you should see + +After executing the API call, you'll receive a JSON response with links to the rendered HTML pages. When you open these pages, you'll see that the spreadsheet is rendered with visible grid lines, making it easier to distinguish between cells. + +### 2. Showing Hidden Rows and Columns + +Spreadsheets often contain hidden rows and columns that may contain important data. GroupDocs.Viewer Cloud lets you control whether these hidden elements are rendered. + +#### Try it yourself + +```bash +# Render spreadsheet with hidden rows and columns visible +curl -v "https://api.groupdocs.cloud/v2.0/viewer/view" \ +-X POST \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +-H "Authorization: Bearer YOUR_JWT_TOKEN" \ +-d "{ + 'FileInfo': { + 'FilePath': 'SampleFiles/with_hidden_row_and_column.xlsx' + }, + 'ViewFormat': 'HTML', + 'RenderOptions': { + 'SpreadsheetOptions': { + 'RenderHiddenColumns': true, + 'RenderHiddenRows': true + } + } +}" +``` + +#### Troubleshooting Tip + +If you're not seeing all the data you expect in the rendered output, it's possible that some content is in hidden rows or columns. Try enabling both `RenderHiddenColumns` and `RenderHiddenRows` to ensure all data is visible. + +### 3. Managing Text Overflow in Cells + +When cells contain more text than can fit within their boundaries, you can control how the overflow is handled. GroupDocs.Viewer Cloud provides several options: + +- HideText: Hides any text that doesn't fit in the cell +- OverlayIfNextIsEmpty: Allows text to overlay subsequent cells if they're empty (default) +- Overlay: Allows text to overlay subsequent cells even if they contain data +- AutoFitColumn: Expands the column width to fit the text + +#### Try it yourself + +```bash +# Render spreadsheet with overflow text hidden +curl -v "https://api.groupdocs.cloud/v2.0/viewer/view" \ +-X POST \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +-H "Authorization: Bearer YOUR_JWT_TOKEN" \ +-d "{ + 'FileInfo': { + 'FilePath': 'SampleFiles/sample.xlsx' + }, + 'ViewFormat': 'HTML', + 'RenderOptions': { + 'SpreadsheetOptions': { + 'TextOverflowMode': 'HideText' + } + } +}" +``` + +#### Learning checkpoint + +What happens if you change the `TextOverflowMode` from `HideText` to `AutoFitColumn`? Try it and observe how the column widths adjust to accommodate the full text content in each cell. + +### 4. Skipping Empty Rows and Columns + +When dealing with large spreadsheets that contain many empty rows or columns, you can improve rendering performance by skipping them. + +#### Try it yourself + +```bash +# Skip rendering empty rows +curl -v "https://api.groupdocs.cloud/v2.0/viewer/view" \ +-X POST \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +-H "Authorization: Bearer YOUR_JWT_TOKEN" \ +-d "{ + 'FileInfo': { + 'FilePath': 'SampleFiles/with_empty_row.xlsx' + }, + 'ViewFormat': 'HTML', + 'RenderOptions': { + 'SpreadsheetOptions': { + 'RenderEmptyRows': false + } + } +}" +``` + +Similarly, you can skip rendering empty columns: + +```bash +# Skip rendering empty columns +curl -v "https://api.groupdocs.cloud/v2.0/viewer/view" \ +-X POST \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +-H "Authorization: Bearer YOUR_JWT_TOKEN" \ +-d "{ + 'FileInfo': { + 'FilePath': 'SampleFiles/with_empty_column.xlsx' + }, + 'ViewFormat': 'HTML', + 'RenderOptions': { + 'SpreadsheetOptions': { + 'RenderEmptyColumns': false + } + } +}" +``` + +### 5. Splitting Worksheets into Pages + +For large worksheets, you can paginate the content by specifying the number of rows to render on each page. + +#### Try it yourself + +```bash +# Split worksheet into pages with 45 rows per page +curl -v "https://api.groupdocs.cloud/v2.0/viewer/view" \ +-X POST \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +-H "Authorization: Bearer YOUR_JWT_TOKEN" \ +-d "{ + 'FileInfo': { + 'FilePath': 'SampleFiles/sample.xlsx' + }, + 'ViewFormat': 'HTML', + 'RenderOptions': { + 'SpreadsheetOptions': { + 'PaginateSheets': true, + 'CountRowsPerPage': 45 + } + } +}" +``` + +#### What you should see + +The response will include multiple page links, with each page containing up to 45 rows from the worksheet. This makes it easier to navigate through large spreadsheets and improves loading performance. + +### 6. Rendering Print Areas Only + +If your spreadsheet has defined print areas, you can choose to render only those sections. + +#### Try it yourself + +```bash +# Render only print areas +curl -v "https://api.groupdocs.cloud/v2.0/viewer/view" \ +-X POST \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +-H "Authorization: Bearer YOUR_JWT_TOKEN" \ +-d "{ + 'FileInfo': { + 'FilePath': 'SampleFiles/with_four_print_areas.xlsx' + }, + 'ViewFormat': 'HTML', + 'RenderOptions': { + 'SpreadsheetOptions': { + 'RenderPrintAreaOnly': true + } + } +}" +``` + +If the spreadsheet has multiple print areas, each print area will be rendered as a separate page. + +## SDK Examples + +### C# Example + +```csharp +// For complete examples, see: https://github.com/groupdocs-viewer-cloud/groupdocs-viewer-cloud-dotnet-samples +string MyClientSecret = "YOUR_CLIENT_SECRET"; +string MyClientId = "YOUR_CLIENT_ID"; + +var configuration = new Configuration(MyClientId, MyClientSecret); +var apiInstance = new ViewApi(configuration); + +// Example: Render spreadsheet with grid lines and show hidden rows/columns +var viewOptions = new ViewOptions +{ + FileInfo = new FileInfo + { + FilePath = "SampleFiles/with_hidden_row_and_column.xlsx" + }, + ViewFormat = ViewOptions.ViewFormatEnum.HTML, + RenderOptions = new HtmlOptions + { + SpreadsheetOptions = new SpreadsheetOptions + { + RenderGridLines = true, + RenderHiddenColumns = true, + RenderHiddenRows = true + } + } +}; + +var response = apiInstance.CreateView(new CreateViewRequest(viewOptions)); +``` + +### Python Example + +```python +# For complete examples, see: https://github.com/groupdocs-viewer-cloud/groupdocs-viewer-cloud-python-samples +import groupdocs_viewer_cloud + +client_id = "YOUR_CLIENT_ID" +client_secret = "YOUR_CLIENT_SECRET" + +apiInstance = groupdocs_viewer_cloud.ViewApi.from_keys(client_id, client_secret) + +# Example: Split worksheets into pages +view_options = groupdocs_viewer_cloud.ViewOptions() +view_options.file_info = groupdocs_viewer_cloud.FileInfo() +view_options.file_info.file_path = "SampleFiles/sample.xlsx" +view_options.view_format = "HTML" +view_options.render_options = groupdocs_viewer_cloud.HtmlOptions() +view_options.render_options.spreadsheet_options = groupdocs_viewer_cloud.SpreadsheetOptions() +view_options.render_options.spreadsheet_options.paginate_sheets = True +view_options.render_options.spreadsheet_options.count_rows_per_page = 45 + +request = groupdocs_viewer_cloud.CreateViewRequest(view_options) +response = apiInstance.create_view(request) +``` + +## What You've Learned + +In this tutorial, you've learned how to: +- Render grid lines in spreadsheets for improved readability +- Show hidden rows and columns for complete data visibility +- Control text overflow behavior in cells +- Optimize rendering by skipping empty rows and columns +- Split large worksheets into manageable pages +- Render only the defined print areas in a spreadsheet + +## Further Practice + +Try combining multiple spreadsheet rendering options in a single request. For example, enable grid lines, show hidden rows, and paginate the worksheet simultaneously to see how these options work together to create a customized viewing experience. + +## Helpful Resources + +- [Product Page](https://products.groupdocs.cloud/viewer/) +- [Documentation](https://docs.groupdocs.cloud/viewer/) +- [API Reference UI](https://reference.groupdocs.cloud/viewer/) +- [Free Support Forum](https://forum.groupdocs.cloud/c/viewer/9) +- [Free Trial](https://dashboard.groupdocs.cloud/#/apps) + +## Feedback and Questions + +If you have questions about this tutorial or any aspect of using GroupDocs.Viewer Cloud API, please visit our [support forum](https://forum.groupdocs.cloud/c/viewer/9). diff --git a/content/viewer/english/advanced-usage/rendering-text-files/_index.md b/content/viewer/english/advanced-usage/rendering-text-files/_index.md new file mode 100644 index 0000000..24a6bba --- /dev/null +++ b/content/viewer/english/advanced-usage/rendering-text-files/_index.md @@ -0,0 +1,262 @@ +--- +title: How to Render Text Files with GroupDocs.Viewer Cloud API Tutorial +url: /advanced-usage/rendering-text-files/ +description: Learn how to render plain text files with proper formatting, line breaks, and character limits in this comprehensive step-by-step tutorial +weight: 130 +--- + +# Tutorial: How to Render Text Files with GroupDocs.Viewer Cloud API + +## Learning Objectives + +In this tutorial, you'll learn how to render plain text files (TXT, CSV, and other text formats) with advanced formatting options using GroupDocs.Viewer Cloud API. By the end of this tutorial, you'll be able to: + +- Render text files with proper formatting +- Control the maximum number of characters per row +- Limit the number of rows per page +- Apply custom styles to rendered text +- Handle different text encodings + +## Prerequisites + +Before starting this tutorial, you should have: + +1. A GroupDocs.Viewer Cloud account (or [sign up for a free trial](https://dashboard.groupdocs.cloud/#/apps)) +2. Your Client ID and Client Secret credentials +3. Sample text files to test with +4. Basic understanding of REST API concepts +5. Familiarity with your preferred programming language (C#, Java, Python, etc.) + +## Use Case Scenario + +Imagine you're developing a code review application that needs to display source code and log files with proper formatting. Users need to view these files with consistent line breaks, character limits, and pagination to ensure readability across different screen sizes. Your application needs to render text files efficiently while maintaining their structure and formatting. + +## Tutorial Steps + +### 1. Basic Text File Rendering + +Let's start by rendering a simple text file with default settings. + +#### Try it yourself + +```bash +# First get JSON Web Token +curl -v "https://api.groupdocs.cloud/connect/token" \ +-X POST \ +-d "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET" \ +-H "Content-Type: application/x-www-form-urlencoded" \ +-H "Accept: application/json" + +# Now render a basic text file +curl -v "https://api.groupdocs.cloud/v2.0/viewer/view" \ +-X POST \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +-H "Authorization: Bearer YOUR_JWT_TOKEN" \ +-d "{ + 'FileInfo': { + 'FilePath': 'SampleFiles/sample.txt' + }, + 'ViewFormat': 'HTML' +}" +``` + +#### What you should see + +After executing the API call, you'll receive a JSON response with links to the rendered HTML pages. When you open these pages, you'll see the text file content rendered with default formatting. + +### 2. Controlling Characters Per Row + +Long lines of text can be difficult to read, especially on smaller screens. GroupDocs.Viewer Cloud allows you to specify the maximum number of characters per row, automatically wrapping text when it exceeds this limit. + +#### Try it yourself + +```bash +curl -v "https://api.groupdocs.cloud/v2.0/viewer/view" \ +-X POST \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +-H "Authorization: Bearer YOUR_JWT_TOKEN" \ +-d "{ + 'FileInfo': { + 'FilePath': 'SampleFiles/sample.txt' + }, + 'ViewFormat': 'HTML', + 'RenderOptions': { + 'TextOptions': { + 'MaxCharsPerRow': 100 + } + } +}" +``` + +This will limit each line to a maximum of 100 characters, wrapping any longer lines. + +#### Troubleshooting Tip + +If you notice that text is being wrapped at odd places, disrupting the reading flow, try adjusting the `MaxCharsPerRow` value. A common practice is to use values between 80 and 120 characters, which is standard for most code style guides. + +### 3. Limiting Rows Per Page + +For very long text files, it's helpful to split the content into multiple pages. You can control how many rows appear on each page using the `MaxRowsPerPage` option. + +#### Try it yourself + +```bash +curl -v "https://api.groupdocs.cloud/v2.0/viewer/view" \ +-X POST \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +-H "Authorization: Bearer YOUR_JWT_TOKEN" \ +-d "{ + 'FileInfo': { + 'FilePath': 'SampleFiles/sample.txt' + }, + 'ViewFormat': 'HTML', + 'RenderOptions': { + 'TextOptions': { + 'MaxRowsPerPage': 100 + } + } +}" +``` + +This will create multiple pages if your text file has more than 100 rows, with each page containing up to 100 rows. + +### 4. Combining Character and Row Limits + +For optimal text rendering, you can combine both character and row limits: + +```bash +curl -v "https://api.groupdocs.cloud/v2.0/viewer/view" \ +-X POST \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +-H "Authorization: Bearer YOUR_JWT_TOKEN" \ +-d "{ + 'FileInfo': { + 'FilePath': 'SampleFiles/sample.txt' + }, + 'ViewFormat': 'HTML', + 'RenderOptions': { + 'TextOptions': { + 'MaxCharsPerRow': 100, + 'MaxRowsPerPage': 100 + } + } +}" +``` + +#### Learning checkpoint + +What would happen if you set a very low value for `MaxCharsPerRow` (e.g., 20) and a low value for `MaxRowsPerPage` (e.g., 10)? Try it and observe how it affects the pagination and overall readability of the text. + +### 5. Choosing the Right Output Format + +For text files, HTML is usually the preferred output format as it preserves formatting better than image formats. However, you can also render text files to images if needed: + +```bash +curl -v "https://api.groupdocs.cloud/v2.0/viewer/view" \ +-X POST \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +-H "Authorization: Bearer YOUR_JWT_TOKEN" \ +-d "{ + 'FileInfo': { + 'FilePath': 'SampleFiles/sample.txt' + }, + 'ViewFormat': 'PNG', + 'RenderOptions': { + 'TextOptions': { + 'MaxCharsPerRow': 100, + 'MaxRowsPerPage': 50 + } + } +}" +``` + +## SDK Examples + +### C# Example + +```csharp +// For complete examples, see: https://github.com/groupdocs-viewer-cloud/groupdocs-viewer-cloud-dotnet-samples +string MyClientSecret = "YOUR_CLIENT_SECRET"; +string MyClientId = "YOUR_CLIENT_ID"; + +var configuration = new Configuration(MyClientId, MyClientSecret); +var apiInstance = new ViewApi(configuration); + +// Example: Render text file with character and row limits +var viewOptions = new ViewOptions +{ + FileInfo = new FileInfo + { + FilePath = "SampleFiles/sample.txt" + }, + ViewFormat = ViewOptions.ViewFormatEnum.HTML, + RenderOptions = new HtmlOptions + { + TextOptions = new TextOptions + { + MaxCharsPerRow = 100, + MaxRowsPerPage = 100 + } + } +}; + +var response = apiInstance.CreateView(new CreateViewRequest(viewOptions)); +``` + +### Python Example + +```python +# For complete examples, see: https://github.com/groupdocs-viewer-cloud/groupdocs-viewer-cloud-python-samples +import groupdocs_viewer_cloud + +client_id = "YOUR_CLIENT_ID" +client_secret = "YOUR_CLIENT_SECRET" + +apiInstance = groupdocs_viewer_cloud.ViewApi.from_keys(client_id, client_secret) + +# Example: Render text file with character and row limits +view_options = groupdocs_viewer_cloud.ViewOptions() +view_options.file_info = groupdocs_viewer_cloud.FileInfo() +view_options.file_info.file_path = "SampleFiles/sample.txt" +view_options.view_format = "HTML" +view_options.render_options = groupdocs_viewer_cloud.HtmlOptions() +view_options.render_options.text_options = groupdocs_viewer_cloud.TextOptions() +view_options.render_options.text_options.max_chars_per_row = 100 +view_options.render_options.text_options.max_rows_per_page = 100 + +request = groupdocs_viewer_cloud.CreateViewRequest(view_options) +response = apiInstance.create_view(request) +``` + +## What You've Learned + +In this tutorial, you've learned how to: +- Render text files with proper formatting +- Control the maximum number of characters per row +- Limit the number of rows per page +- Choose the right output format for text rendering + +## Further Practice + +Try experimenting with different values for `MaxCharsPerRow` and `MaxRowsPerPage` to find the optimal settings for different types of text content. For example, code files might benefit from different settings than log files or plain text documents. + +## Next Steps + +You've now completed our tutorial series on advanced usage of GroupDocs.Viewer Cloud API! To continue your learning journey, explore our comprehensive [API documentation](https://docs.groupdocs.cloud/viewer/) or check out our other product tutorials. + +## Helpful Resources + +- [Product Page](https://products.groupdocs.cloud/viewer/) +- [Documentation](https://docs.groupdocs.cloud/viewer/) +- [API Reference UI](https://reference.groupdocs.cloud/viewer/) +- [Free Support Forum](https://forum.groupdocs.cloud/c/viewer/9) +- [Free Trial](https://dashboard.groupdocs.cloud/#/apps) + +## Feedback and Questions + +If you have questions about this tutorial or any aspect of using GroupDocs.Viewer Cloud API, please visit our [support forum](https://forum.groupdocs.cloud/c/viewer/9). diff --git a/content/viewer/english/advanced-usage/rendering-word-documents/_index.md b/content/viewer/english/advanced-usage/rendering-word-documents/_index.md new file mode 100644 index 0000000..0542df8 --- /dev/null +++ b/content/viewer/english/advanced-usage/rendering-word-documents/_index.md @@ -0,0 +1,266 @@ +--- +title: How to Render Word Processing Documents with GroupDocs.Viewer Cloud API Tutorial +url: /advanced-usage/rendering-word-documents/ +description: Learn how to render Word documents with tracked changes, comments, and other specialized formatting in this step-by-step tutorial using GroupDocs.Viewer Cloud API +weight: 90 +--- + +# Tutorial: How to Render Word Processing Documents with GroupDocs.Viewer Cloud API + +## Learning Objectives + +In this tutorial, you'll learn how to render Word and other word processing documents with advanced options using GroupDocs.Viewer Cloud API. By the end of this tutorial, you'll be able to: + +- Render Word documents with tracked changes +- Control the display of comments and annotations +- Customize paragraph and heading formatting +- Handle document revisions +- Work with complex document elements like tables and graphics + +## Prerequisites + +Before starting this tutorial, you should have: + +1. A GroupDocs.Viewer Cloud account (or [sign up for a free trial](https://dashboard.groupdocs.cloud/#/apps)) +2. Your Client ID and Client Secret credentials +3. Sample Word documents to test with (DOCX, DOC, etc.) +4. Basic understanding of REST API concepts +5. Familiarity with your preferred programming language (C#, Java, Python, etc.) + +## Use Case Scenario + +Imagine you're developing a document review system where team members collaborate on Word documents using tracked changes and comments. Your application needs to display these documents along with all revision marks so reviewers can see what changes have been made and by whom. You also need to ensure that the formatting is preserved accurately. + +## Tutorial Steps + +### 1. Rendering Documents with Tracked Changes + +Word documents often contain tracked changes (additions, deletions, and formatting changes) that users want to see when reviewing the document. By default, GroupDocs.Viewer Cloud doesn't render these tracked changes, but you can enable this feature. + +#### Try it yourself + +```bash +# First get JSON Web Token +curl -v "https://api.groupdocs.cloud/connect/token" \ +-X POST \ +-d "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET" \ +-H "Content-Type: application/x-www-form-urlencoded" \ +-H "Accept: application/json" + +# Now render the Word document with tracked changes visible +curl -v "https://api.groupdocs.cloud/v2.0/viewer/view" \ +-X POST \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +-H "Authorization: Bearer YOUR_JWT_TOKEN" \ +-d "{ + 'FileInfo': { + 'FilePath': 'SampleFiles/with_tracked_changes.docx' + }, + 'ViewFormat': 'HTML', + 'RenderOptions': { + 'WordProcessingOptions': { + 'RenderTrackedChanges': true + } + } +}" +``` + +#### What you should see + +After executing the API call, you'll receive a JSON response with links to the rendered HTML pages. When you open these pages, you'll see the Word document with all tracked changes visible, including additions, deletions, and formatting modifications. Each change will typically be highlighted or marked in a similar way to how Microsoft Word displays tracked changes. + +#### Troubleshooting Tip + +If tracked changes are not appearing in your rendered output, verify that: +1. The document actually contains tracked changes +2. You've set `RenderTrackedChanges` to `true` +3. You're using HTML as the output format (this feature works best with HTML rendering) + +### 2. Customizing Word Processing Options + +GroupDocs.Viewer Cloud API provides several options for customizing the rendering of Word documents: + +#### Rendering Comments + +Like tracked changes, comments in Word documents are not rendered by default. You can enable them using: + +```bash +curl -v "https://api.groupdocs.cloud/v2.0/viewer/view" \ +-X POST \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +-H "Authorization: Bearer YOUR_JWT_TOKEN" \ +-d "{ + 'FileInfo': { + 'FilePath': 'SampleFiles/document_with_comments.docx' + }, + 'ViewFormat': 'HTML', + 'RenderOptions': { + 'WordProcessingOptions': { + 'RenderComments': true + } + } +}" +``` + +#### Handling Headers and Footers + +You can control whether headers and footers are displayed in the rendered document: + +```bash +curl -v "https://api.groupdocs.cloud/v2.0/viewer/view" \ +-X POST \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +-H "Authorization: Bearer YOUR_JWT_TOKEN" \ +-d "{ + 'FileInfo': { + 'FilePath': 'SampleFiles/document_with_header_footer.docx' + }, + 'ViewFormat': 'HTML', + 'RenderOptions': { + 'WordProcessingOptions': { + 'RenderHeaders': true, + 'RenderFooters': true + } + } +}" +``` + +### 3. Working with Multiple Document Formats + +GroupDocs.Viewer Cloud supports various Word processing formats including DOCX, DOC, RTF, ODT, and more. The rendering options work across these formats: + +#### Rendering RTF Documents + +```bash +curl -v "https://api.groupdocs.cloud/v2.0/viewer/view" \ +-X POST \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +-H "Authorization: Bearer YOUR_JWT_TOKEN" \ +-d "{ + 'FileInfo': { + 'FilePath': 'SampleFiles/sample.rtf' + }, + 'ViewFormat': 'HTML', + 'RenderOptions': { + 'WordProcessingOptions': { + 'RenderTrackedChanges': true + } + } +}" +``` + +#### Learning checkpoint + +How would you modify the API call to render a Word document with both tracked changes and comments visible? Try combining multiple WordProcessingOptions in a single request. + +### 4. Advanced Document Features + +Beyond tracked changes and comments, GroupDocs.Viewer Cloud can handle other advanced Word document features: + +#### Document Revisions + +For documents with multiple revisions, you can specify which revision to render: + +```bash +curl -v "https://api.groupdocs.cloud/v2.0/viewer/view" \ +-X POST \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +-H "Authorization: Bearer YOUR_JWT_TOKEN" \ +-d "{ + 'FileInfo': { + 'FilePath': 'SampleFiles/document_with_revisions.docx' + }, + 'ViewFormat': 'HTML' +}" +``` + +## SDK Examples + +### C# Example + +```csharp +// For complete examples, see: https://github.com/groupdocs-viewer-cloud/groupdocs-viewer-cloud-dotnet-samples +string MyClientSecret = "YOUR_CLIENT_SECRET"; +string MyClientId = "YOUR_CLIENT_ID"; + +var configuration = new Configuration(MyClientId, MyClientSecret); +var apiInstance = new ViewApi(configuration); + +// Example: Render Word document with tracked changes +var viewOptions = new ViewOptions +{ + FileInfo = new FileInfo + { + FilePath = "SampleFiles/with_tracked_changes.docx" + }, + ViewFormat = ViewOptions.ViewFormatEnum.HTML, + RenderOptions = new HtmlOptions + { + WordProcessingOptions = new WordProcessingOptions + { + RenderTrackedChanges = true + } + } +}; + +var response = apiInstance.CreateView(new CreateViewRequest(viewOptions)); +``` + +### Python Example + +```python +# For complete examples, see: https://github.com/groupdocs-viewer-cloud/groupdocs-viewer-cloud-python-samples +import groupdocs_viewer_cloud + +client_id = "YOUR_CLIENT_ID" +client_secret = "YOUR_CLIENT_SECRET" + +apiInstance = groupdocs_viewer_cloud.ViewApi.from_keys(client_id, client_secret) + +# Example: Render Word document with tracked changes and comments +view_options = groupdocs_viewer_cloud.ViewOptions() +view_options.file_info = groupdocs_viewer_cloud.FileInfo() +view_options.file_info.file_path = "SampleFiles/with_tracked_changes.docx" +view_options.view_format = "HTML" +view_options.render_options = groupdocs_viewer_cloud.HtmlOptions() +view_options.render_options.word_processing_options = groupdocs_viewer_cloud.WordProcessingOptions() +view_options.render_options.word_processing_options.render_tracked_changes = True +view_options.render_options.word_processing_options.render_comments = True + +request = groupdocs_viewer_cloud.CreateViewRequest(view_options) +response = apiInstance.create_view(request) +``` + +## What You've Learned + +In this tutorial, you've learned how to: +- Render Word documents with tracked changes visible +- Display comments and annotations in rendered documents +- Control the visibility of headers and footers +- Work with different Word processing formats +- Handle document revisions + +## Further Practice + +Try rendering Word documents with different combinations of options to see how they affect the output. For example, enable tracked changes but disable headers and footers, or render comments but hide tracked changes. Experiment with different output formats (HTML, PDF, PNG) to see how they handle these advanced features. + +## Next Tutorial + +Continue your learning journey with our [Tutorial on Rendering Outlook Data Files](/advanced-usage/rendering-outlook-files/), where you'll discover techniques for handling email content and attachments. + +## Helpful Resources + +- [Product Page](https://products.groupdocs.cloud/viewer/) +- [Documentation](https://docs.groupdocs.cloud/viewer/) +- [API Reference UI](https://reference.groupdocs.cloud/viewer/) +- [Free Support Forum](https://forum.groupdocs.cloud/c/viewer/9) +- [Free Trial](https://dashboard.groupdocs.cloud/#/apps) + +## Feedback and Questions + +If you have questions about this tutorial or any aspect of using GroupDocs.Viewer Cloud API, please visit our [support forum](https://forum.groupdocs.cloud/c/viewer/9). diff --git a/content/viewer/english/advanced-usage/reorder-pages/_index.md b/content/viewer/english/advanced-usage/reorder-pages/_index.md new file mode 100644 index 0000000..b8b0cd9 --- /dev/null +++ b/content/viewer/english/advanced-usage/reorder-pages/_index.md @@ -0,0 +1,301 @@ +--- +title: How to Reorder Pages in GroupDocs.Viewer Cloud Tutorial +url: /advanced-usage/reorder-pages/ +description: Learn how to customize page order when rendering documents with GroupDocs.Viewer Cloud API in this step-by-step tutorial for developers. +weight: 110 +--- + +## Tutorial: How to Reorder Document Pages + +In this tutorial, you'll learn how to reorder pages when rendering documents with GroupDocs.Viewer Cloud API. This allows you to present document pages in a different sequence than they appear in the original file, which can be useful for custom presentations, comparing pages, or reorganizing content. + +## Learning Objectives + +By the end of this tutorial, you'll be able to: +- Specify a custom order for document pages when rendering +- Render selected pages in any sequence you choose +- Implement custom page ordering across different document types +- Combine page reordering with other rendering options + +## Prerequisites + +Before you begin this tutorial, you need: + +1. A GroupDocs.Viewer Cloud account (if you don't have one, [sign up for a free trial](https://dashboard.groupdocs.cloud/#/apps)) +2. Your Client ID and Client Secret credentials from the GroupDocs Cloud Dashboard +3. Basic understanding of REST APIs +4. Development environment for your preferred language (C#, Java, Python, etc.) +5. [GroupDocs.Viewer Cloud SDK](https://github.com/groupdocs-viewer-cloud) installed for your language of choice + +## The Practical Scenario + +Imagine you're building a document comparison tool where users need to compare specific pages that aren't consecutive in the original document. For instance, a user wants to compare page 5 with page 2 side-by-side. Your application needs to render these pages in the requested order rather than their original sequence. + +## Step 1: Understanding Page Reordering + +GroupDocs.Viewer Cloud uses the `PagesToRender` property to specify which pages to render and in what order. This property takes a list of page numbers, and the rendering will follow exactly the sequence you provide. + +Key points about page reordering: +- Page numbers start from 1 (not 0-based) +- You can render the same page multiple times if needed +- Pages will be rendered in exactly the order specified +- You can combine this with other rendering options + +## Step 2: Set Up Your Project + +First, set up authentication with your Client ID and Client Secret: + +```csharp +// For complete examples and data files, please go to https://github.com/groupdocs-viewer-cloud/groupdocs-viewer-cloud-dotnet-samples +string MyClientSecret = ""; // Get your Client Secret from https://dashboard.groupdocs.cloud +string MyClientId = ""; // Get your Client ID from https://dashboard.groupdocs.cloud + +var configuration = new Configuration(MyClientId, MyClientSecret); +var apiInstance = new ViewApi(configuration); +``` + +## Step 3: Reordering Pages - Basic Example + +Let's render pages 2 and 1 in reverse order (2 first, then 1): + +```csharp +var viewOptions = new ViewOptions +{ + FileInfo = new FileInfo + { + FilePath = "sample.docx" // Document in your cloud storage + }, + ViewFormat = ViewOptions.ViewFormatEnum.HTML, + + RenderOptions = new RenderOptions + { + PagesToRender = new List {2, 1} // Render page 2 first, then page 1 + } +}; + +var response = apiInstance.CreateView(new CreateViewRequest(viewOptions)); +``` + +## Step 4: Rendering Non-Sequential Pages + +Now, let's render pages in a completely custom order, for example pages 4, 2, and 8: + +```csharp +var viewOptions = new ViewOptions +{ + FileInfo = new FileInfo + { + FilePath = "sample.docx" + }, + ViewFormat = ViewOptions.ViewFormatEnum.HTML, + + RenderOptions = new RenderOptions + { + PagesToRender = new List {4, 2, 8} // Render pages 4, 2, and 8 in that order + } +}; + +var response = apiInstance.CreateView(new CreateViewRequest(viewOptions)); +``` + +## Step 5: Rendering the Same Page Multiple Times + +In some scenarios, you might want to render the same page multiple times. This can be useful for comparison or emphasis: + +```csharp +var viewOptions = new ViewOptions +{ + FileInfo = new FileInfo + { + FilePath = "sample.docx" + }, + ViewFormat = ViewOptions.ViewFormatEnum.HTML, + + RenderOptions = new RenderOptions + { + PagesToRender = new List {3, 3, 3} // Render page 3 three times + } +}; + +var response = apiInstance.CreateView(new CreateViewRequest(viewOptions)); +``` + +## Step 6: Reordering Pages with PDF Output + +The same page reordering works when rendering to PDF. This example renders pages 5, 2, and 1 in that order to a PDF document: + +```csharp +var viewOptions = new ViewOptions +{ + FileInfo = new FileInfo + { + FilePath = "sample.docx" + }, + ViewFormat = ViewOptions.ViewFormatEnum.PDF, + + RenderOptions = new RenderOptions + { + PagesToRender = new List {5, 2, 1} // Render pages 5, 2, and 1 in that order + } +}; + +var response = apiInstance.CreateView(new CreateViewRequest(viewOptions)); +``` + +## Try It Yourself + +Now it's your turn to experiment with page reordering: + +1. Try creating a document with pages in reverse order (last to first) +2. Implement a "key pages" feature that extracts and renders only specific important pages +3. Create a before/after comparison by rendering the same page twice +4. Combine page reordering with other options like watermarking + +## Common Issues and Troubleshooting + +Issue: Specified page number is beyond the document's page count +Solution: The API will skip invalid page numbers. Make sure to check the document's total page count first. + +Issue: Empty result when all page numbers are invalid +Solution: Ensure at least one valid page number is included in your PagesToRender list. + +Issue: Original page order is maintained despite specifying PagesToRender +Solution: Check that you're passing the page numbers as a collection/array/list, not as separate parameters. + +## Complete Code Examples + +### cURL Example + +```bash +# First get JSON Web Token +curl -v "https://api.groupdocs.cloud/connect/token" \ +-X POST \ +-d "grant_type=client_credentials&client_id=xxxx&client_secret=xxxx" \ +-H "Content-Type: application/x-www-form-urlencoded" \ +-H "Accept: application/json" + +# Reorder pages +curl -v "https://api.groupdocs.cloud/v2.0/viewer/view" \ +-X POST \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +-H "Authorization: Bearer " \ +-d "{ + 'FileInfo': { + 'FilePath': 'sample.docx' + }, + 'ViewFormat': 'HTML', + 'RenderOptions': { + 'PagesToRender': [2, 1] + } +}" +``` + +### SDK Examples + +#### C# Example + +```csharp +// For complete examples and data files, please go to https://github.com/groupdocs-viewer-cloud/groupdocs-viewer-cloud-dotnet-samples +string MyClientSecret = ""; // Get Client Id and Client Secret from https://dashboard.groupdocs.cloud +string MyClientId = ""; // Get Client Id and Client Secret from https://dashboard.groupdocs.cloud + +var configuration = new Configuration(MyClientId, MyClientSecret); +var apiInstance = new ViewApi(configuration); + +var viewOptions = new ViewOptions +{ + FileInfo = new FileInfo + { + FilePath = "sample.docx" + }, + ViewFormat = ViewOptions.ViewFormatEnum.HTML, + + RenderOptions = new RenderOptions + { + // Pass page numbers in the order you want to render them + PagesToRender = new List {2, 1} + } +}; + +var response = apiInstance.CreateView(new CreateViewRequest(viewOptions)); +``` + +#### Python Example + +```python +# For complete examples and data files, please go to https://github.com/groupdocs-viewer-cloud/groupdocs-viewer-cloud-python-samples +import groupdocs_viewer_cloud + +client_id = "XXXX-XXXX-XXXX-XXXX" # Get Client Id and Client Secret from https://dashboard.groupdocs.cloud +client_secret = "XXXXXXXXXXXXXXXX" # Get Client Id and Client Secret from https://dashboard.groupdocs.cloud + +apiInstance = groupdocs_viewer_cloud.ViewApi.from_keys(client_id, client_secret) + +view_options = groupdocs_viewer_cloud.ViewOptions() +view_options.file_info = groupdocs_viewer_cloud.FileInfo() +view_options.file_info.file_path = "sample.docx" +view_options.view_format = "HTML" +view_options.render_options = groupdocs_viewer_cloud.HtmlOptions() +# Pass page numbers in the order you want to render them +view_options.render_options.pages_to_render = [2, 1] + +request = groupdocs_viewer_cloud.CreateViewRequest(view_options) +response = apiInstance.create_view(request) +``` + +#### Java Example + +```java +// For complete examples and data files, please go to https://github.com/groupdocs-viewer-cloud/groupdocs-viewer-cloud-java-samples +String MyClientSecret = ""; // Get Client Id and Client Secret from https://dashboard.groupdocs.cloud +String MyClientId = ""; // Get Client Id and Client Secret from https://dashboard.groupdocs.cloud + +Configuration configuration = new Configuration(MyClientId, MyClientSecret); +ViewApi apiInstance = new ViewApi(configuration); + +FileInfo fileInfo = new FileInfo(); +fileInfo.setFilePath("sample.docx"); +ViewOptions viewOptions = new ViewOptions(); +viewOptions.setFileInfo(fileInfo); +viewOptions.setViewFormat(ViewFormatEnum.HTML); +RenderOptions renderOptions = new RenderOptions(); +// Pass page numbers in the order you want to render them +renderOptions.addPagesToRenderItem(2); +renderOptions.addPagesToRenderItem(1); +viewOptions.setRenderOptions(renderOptions); + +ViewResult response = apiInstance.createView(new CreateViewRequest(viewOptions)); +``` + +## What You've Learned + +In this tutorial, you've learned: + +- How to render document pages in a custom order +- Ways to select and arrange specific pages for rendering +- How to repeat pages in the rendered output +- Techniques for implementing page reordering across different output formats + +## Further Practice + +To solidify your knowledge, try these exercises: + +1. Create a document viewer that allows users to drag and drop pages to rearrange their order +2. Build a document comparison tool that places selected pages side by side +3. Implement a feature that highlights important pages by extracting and placing them at the beginning +4. Create a presentation mode that rearranges pages for optimal viewing flow + +## Helpful Resources + +- [Product Page](https://products.groupdocs.cloud/viewer/) +- [Documentation](https://docs.groupdocs.cloud/viewer/) +- [Live Demo](https://products.groupdocs.app/viewer/family) +- [API Reference UI](https://reference.groupdocs.cloud/viewer/) +- [Blog](https://blog.groupdocs.cloud/categories/groupdocs.viewer-cloud-product-family/) +- [Free Support](https://forum.groupdocs.cloud/c/viewer/9) +- [Free Trial](https://dashboard.groupdocs.cloud/#/apps) + +## Feedback and Questions + +Did you find this tutorial helpful? Do you have questions about implementing page reordering in your application? Let us know in the [GroupDocs.Viewer Cloud forum](https://forum.groupdocs.cloud/c/viewer/9). diff --git a/content/viewer/english/basic-usage/_index.md b/content/viewer/english/basic-usage/_index.md new file mode 100644 index 0000000..afefadd --- /dev/null +++ b/content/viewer/english/basic-usage/_index.md @@ -0,0 +1,58 @@ +--- +title: GroupDocs.Viewer Cloud API Document Basic Usage Tutorials +weight: 2 +description: Learn to use GroupDocs.Viewer Cloud API with these step-by-step tutorials covering document rendering, HTML, PDF, and image conversion +url: /basic-usage/ +--- + +# GroupDocs.Viewer Cloud API Document Basic Usage Tutorials + +Welcome to our hands-on tutorial series on using GroupDocs.Viewer Cloud API! This collection of step-by-step guides is designed to help developers quickly master the essential capabilities of our document viewing solution. + +## Getting Started with the Tutorials + +These tutorials follow a progressive learning path, building from basic operations to more advanced features. Whether you're new to GroupDocs.Viewer Cloud or looking to deepen your expertise, you'll find practical guidance for implementing document viewing solutions in your applications. + +Each tutorial provides clear code examples in multiple programming languages, detailed explanations, and practical use cases to enhance your learning experience. + +## Learning Path + +### Foundation Tutorials +1. [Learn to Retrieve Document Information](/basic-usage/get-document-information/) - Learn how to obtain basic information about documents including format, page count, and properties +2. [Get Supported File Formats Tutorial](/basic-usage/get-supported-file-formats/) - Discover how to retrieve the complete list of file formats supported by GroupDocs.Viewer Cloud + + +### HTML Viewer Tutorials +1. [HTML Viewer Basics Tutorial](/basic-usage/html-viewer/) - Learn the fundamentals of rendering documents to HTML format +2. [Responsive HTML Layout Tutorial](/basic-usage/html-viewer-responsive-layout/) - Create responsive HTML views that adapt to different screen sizes + + +### Image Viewer Tutorials +1. [Image Viewer Basics Tutorial](/basic-usage/image-viewer/) - Learn to render documents to various image formats + + +### PDF Viewer Tutorials +1. [PDF Viewer Basics Tutorial](/basic-usage/pdf-viewer/) - Master rendering documents to PDF format +2. [PDF Security Implementation Tutorial](/basic-usage/pdf-viewer-protect/) - Learn to secure PDF documents with passwords and permissions + +## Prerequisites + +Before starting these tutorials, make sure you have: + +- A GroupDocs Cloud account (get your [free trial here](https://dashboard.groupdocs.cloud/#/apps)) +- Your Client ID and Client Secret (available from your [dashboard](https://dashboard.groupdocs.cloud/#/apps)) +- Basic knowledge of REST APIs and your programming language of choice + +## Helpful Resources + +- [Product Page](https://products.groupdocs.cloud/viewer/) +- [Documentation](https://docs.groupdocs.cloud/viewer/) +- [Live Demo](https://products.groupdocs.app/viewer/family) +- [API Reference](https://reference.groupdocs.cloud/viewer/) +- [Blog](https://blog.groupdocs.cloud/categories/groupdocs.viewer-cloud-product-family/) +- [Free Support Forum](https://forum.groupdocs.cloud/c/viewer/9) +- [Free Trial](https://dashboard.groupdocs.cloud/#/apps) + +## Feedback and Questions + +Have questions about these tutorials? Found something unclear? We welcome your feedback and questions on our [support forum](https://forum.groupdocs.cloud/c/viewer/9). diff --git a/content/viewer/english/basic-usage/get-document-information/_index.md b/content/viewer/english/basic-usage/get-document-information/_index.md new file mode 100644 index 0000000..d9d072e --- /dev/null +++ b/content/viewer/english/basic-usage/get-document-information/_index.md @@ -0,0 +1,697 @@ +--- +title: How to Retrieve Document Information with GroupDocs.Viewer Cloud API Tutorial +url: /basic-usage/get-document-information/ +description: Learn how to retrieve comprehensive document information including format, page count, and properties using GroupDocs.Viewer Cloud API in this step-by-step tutorial +weight: 3 +--- + +# Tutorial: How to Retrieve Document Information with GroupDocs.Viewer Cloud API + +## Learning Objectives + +In this tutorial, you'll learn how to: +- Retrieve basic information about documents using GroupDocs.Viewer Cloud API +- Extract document properties like format, page count, and page dimensions +- Get text coordinates for implementing text search and selection +- Access attachment information for documents with embedded files +- Utilize document information in your applications + +## Prerequisites + +Before starting this tutorial, you should have: +- A GroupDocs.Viewer Cloud account (get your [free trial here](https://dashboard.groupdocs.cloud/#/apps)) +- Your Client ID and Client Secret +- Basic understanding of REST APIs +- Familiarity with your programming language of choice (C#, Java, Python, PHP, Ruby, Node.js, or Go) +- A document for testing (we'll use a sample DOCX in this tutorial) + +## Why Document Information Matters + +Retrieving document information is often a crucial first step in document processing workflows. Having accurate metadata allows you to: + +- Plan rendering operations: Knowing page count and dimensions helps properly configure viewing options +- Implement pagination: Page information enables efficient navigation in multi-page documents +- Enable text search: Text coordinates make text selection and search possible +- Handle attachments: Awareness of embedded files allows for complete document processing +- Validate compatibility: File format detection ensures the document can be properly processed + +GroupDocs.Viewer Cloud API provides a simple and efficient way to extract this valuable information before you begin the rendering process. + +## Step 1: Upload Your Document to Cloud Storage + +Before retrieving document information, you need to upload a document to GroupDocs.Viewer Cloud storage. + +```bash +# First get JSON Web Token +curl -v "https://api.groupdocs.cloud/connect/token" \ +-X POST \ +-d "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET" \ +-H "Content-Type: application/x-www-form-urlencoded" \ +-H "Accept: application/json" + +# Store JWT in a variable for reuse +JWT="YOUR_JWT_TOKEN" + +# Upload file to storage +curl -v "https://api.groupdocs.cloud/v2.0/viewer/storage/file/SampleFiles/sample.docx" \ +-X PUT \ +-H "Content-Type: multipart/form-data" \ +-H "Accept: application/json" \ +-H "Authorization: Bearer $JWT" \ +--data-binary "@/path/to/your/sample.docx" +``` + +## Step 2: Retrieve Document Information + +Now, let's use the API to retrieve comprehensive information about the document: + +```bash +curl -v "https://api.groupdocs.cloud/v2.0/viewer/info" \ +-X POST \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +-H "Authorization: Bearer $JWT" \ +-d "{ + 'FileInfo': { + 'FilePath': 'SampleFiles/sample.docx' + }, + 'ViewFormat': 'HTML' +}" +``` + +### Understanding the Response + +The API returns detailed information about the document: + +```json +{ + "formatExtension": ".docx", + "format": "Microsoft Word Open XML Document", + "pages": [ + { + "number": 1, + "width": 595, + "height": 841, + "visible": true, + "lines": [] + }, + { + "number": 2, + "width": 595, + "height": 841, + "visible": true, + "lines": [] + }, + { + "number": 3, + "width": 595, + "height": 841, + "visible": true, + "lines": [] + } + ], + "attachments": [], + "archiveViewInfo": null, + "cadViewInfo": null, + "projectManagementViewInfo": null, + "outlookViewInfo": null, + "pdfViewInfo": null +} +``` + +Key information included in the response: +- Format: The document's format name and extension +- Pages: Details about each page, including number, dimensions, and visibility +- Attachments: List of any embedded files (empty for our example document) +- Specialized Info: Additional format-specific information for special formats (null for our example) + +## Step 3: Retrieving Text Coordinates + +If you need text coordinates for implementing text selection or search functionality, you can set the `ExtractText` parameter to `true`: + +```bash +curl -v "https://api.groupdocs.cloud/v2.0/viewer/info" \ +-X POST \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +-H "Authorization: Bearer $JWT" \ +-d "{ + 'FileInfo': { + 'FilePath': 'SampleFiles/sample.docx' + }, + 'ViewFormat': 'PNG', + 'RenderOptions': { + 'ExtractText': true + } +}" +``` + +With text extraction enabled, the response will include detailed text information: + +```json +{ + "formatExtension": ".docx", + "format": "Microsoft Word Open XML Document", + "pages": [ + { + "number": 1, + "width": 595, + "height": 841, + "visible": true, + "lines": [ + { + "words": [ + { + "characters": [ + { + "x": 229.607, + "y": 67.8, + "width": 10.674, + "height": 19.8, + "value": "T" + }, + // More characters... + ], + "x": 229.607, + "y": 67.8, + "width": 39.721, + "height": 19.8, + "value": "This" + }, + // More words... + ], + "x": 229.607, + "y": 67.8, + "width": 136.387, + "height": 19.8, + "value": "This is a sample" + }, + // More lines... + ] + }, + // More pages... + ], + "attachments": [], + "archiveViewInfo": null, + "cadViewInfo": null, + "projectManagementViewInfo": null, + "outlookViewInfo": null, + "pdfViewInfo": null +} +``` + +This hierarchical structure provides coordinates for: +- Lines of text +- Words within each line +- Individual characters within each word + +## Step 4: Working with Document Attachments + +For documents that contain attachments (like emails or archives), the API will return information about these embedded files: + +```bash +curl -v "https://api.groupdocs.cloud/v2.0/viewer/info" \ +-X POST \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +-H "Authorization: Bearer $JWT" \ +-d "{ + 'FileInfo': { + 'FilePath': 'SampleFiles/with_attachments.msg' + }, + 'ViewFormat': 'HTML' +}" +``` + +For a document with attachments, the response will include attachment details: + +```json +{ + "formatExtension": ".msg", + "format": "Microsoft Outlook Message", + "pages": [ + { + "number": 1, + "width": 612, + "height": 792, + "visible": true, + "lines": [] + } + ], + "attachments": [ + { + "name": "attachment-image.png", + "filePath": null + }, + { + "name": "attachment-word.doc", + "filePath": null + } + ], + "archiveViewInfo": null, + "cadViewInfo": null, + "projectManagementViewInfo": null, + "outlookViewInfo": { + "folders": [] + }, + "pdfViewInfo": null +} +``` + +## Step 5: Implement in Your Application + +Now let's implement document information retrieval in a real application using one of our supported SDKs. + +### C# Example + +```csharp +using GroupDocs.Viewer.Cloud.Sdk.Api; +using GroupDocs.Viewer.Cloud.Sdk.Client; +using GroupDocs.Viewer.Cloud.Sdk.Model; +using GroupDocs.Viewer.Cloud.Sdk.Model.Requests; +using System; +using System.Collections.Generic; +using System.IO; + +namespace GroupDocs.Viewer.Cloud.Tutorial +{ + class Program + { + static void Main(string[] args) + { + // Get your client ID and client secret from https://dashboard.groupdocs.cloud/ + string MyClientId = "YOUR_CLIENT_ID"; + string MyClientSecret = "YOUR_CLIENT_SECRET"; + + // Create API instance + var configuration = new Configuration(MyClientId, MyClientSecret); + var apiInstance = new InfoApi(configuration); + + // Define view options + var viewOptions = new ViewOptions + { + FileInfo = new FileInfo + { + FilePath = "SampleFiles/sample.docx" + }, + ViewFormat = ViewOptions.ViewFormatEnum.HTML + }; + + try + { + // Call the API to get document information + var response = apiInstance.GetInfo(new GetInfoRequest(viewOptions)); + + Console.WriteLine("Document information retrieved successfully!"); + + // Display basic document information + Console.WriteLine($"Format: {response.Format} ({response.FormatExtension})"); + Console.WriteLine($"Total pages: {response.Pages.Count}"); + + // Display information about each page + Console.WriteLine("\nPage information:"); + foreach (var page in response.Pages) + { + Console.WriteLine($" Page {page.Number}: {page.Width}x{page.Height} pixels, Visible: {page.Visible}"); + } + + // Display attachment information if any + if (response.Attachments != null && response.Attachments.Count > 0) + { + Console.WriteLine("\nAttachments:"); + foreach (var attachment in response.Attachments) + { + Console.WriteLine($" {attachment.Name}"); + } + } + else + { + Console.WriteLine("\nNo attachments found."); + } + + // Display format-specific information if available + if (response.PdfViewInfo != null) + { + Console.WriteLine("\nPDF-specific information available."); + } + if (response.ArchiveViewInfo != null) + { + Console.WriteLine("\nArchive-specific information available."); + } + if (response.CadViewInfo != null) + { + Console.WriteLine("\nCAD-specific information available."); + } + if (response.ProjectManagementViewInfo != null) + { + Console.WriteLine("\nProject Management-specific information available."); + } + if (response.OutlookViewInfo != null) + { + Console.WriteLine("\nOutlook-specific information available."); + } + } + catch (Exception e) + { + Console.WriteLine("Exception while calling InfoApi: " + e.Message); + } + + Console.WriteLine("\nPress any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +### Python Example + +```python +# Import modules +import groupdocs_viewer_cloud + +# Get your client ID and client secret from https://dashboard.groupdocs.cloud/ +client_id = "YOUR_CLIENT_ID" +client_secret = "YOUR_CLIENT_SECRET" + +# Create API instance +api_instance = groupdocs_viewer_cloud.InfoApi.from_keys(client_id, client_secret) + +# Define view options +view_options = groupdocs_viewer_cloud.ViewOptions() +view_options.file_info = groupdocs_viewer_cloud.FileInfo() +view_options.file_info.file_path = "SampleFiles/sample.docx" +view_options.view_format = "HTML" + +try: + # Call the API to get document information + request = groupdocs_viewer_cloud.GetInfoRequest(view_options) + response = api_instance.get_info(request) + + print("Document information retrieved successfully!") + + # Display basic document information + print(f"Format: {response.format} ({response.format_extension})") + print(f"Total pages: {len(response.pages)}") + + # Display information about each page + print("\nPage information:") + for page in response.pages: + print(f" Page {page.number}: {page.width}x{page.height} pixels, Visible: {page.visible}") + + # Display attachment information if any + if response.attachments and len(response.attachments) > 0: + print("\nAttachments:") + for attachment in response.attachments: + print(f" {attachment.name}") + else: + print("\nNo attachments found.") + + # Display format-specific information if available + if response.pdf_view_info: + print("\nPDF-specific information available.") + if response.archive_view_info: + print("\nArchive-specific information available.") + if response.cad_view_info: + print("\nCAD-specific information available.") + if response.project_management_view_info: + print("\nProject Management-specific information available.") + if response.outlook_view_info: + print("\nOutlook-specific information available.") + +except groupdocs_viewer_cloud.ApiException as e: + print(f"Exception while calling InfoApi: {e}") +``` + +## Step 6: Extracting Text Coordinates for Selection + +If you need to implement text selection functionality, you'll need detailed text coordinates. Let's modify our code to extract text data: + +### C# Example with Text Extraction + +```csharp +// Define view options with text extraction enabled +var viewOptions = new ViewOptions +{ + FileInfo = new FileInfo + { + FilePath = "SampleFiles/sample.docx" + }, + ViewFormat = ViewOptions.ViewFormatEnum.PNG, + RenderOptions = new ImageOptions + { + ExtractText = true + } +}; + +try +{ + // Call the API to get document information with text coordinates + var response = apiInstance.GetInfo(new GetInfoRequest(viewOptions)); + + Console.WriteLine("Document information with text coordinates retrieved successfully!"); + + // Process text information for the first page (as an example) + if (response.Pages.Count > 0 && response.Pages[0].Lines != null && response.Pages[0].Lines.Count > 0) + { + Console.WriteLine("\nText content of the first page:"); + + foreach (var line in response.Pages[0].Lines) + { + Console.WriteLine($"Line: \"{line.Value}\""); + Console.WriteLine($" Position: X={line.X}, Y={line.Y}, Width={line.Width}, Height={line.Height}"); + + Console.WriteLine(" Words:"); + foreach (var word in line.Words) + { + Console.WriteLine($" Word: \"{word.Value}\""); + Console.WriteLine($" Position: X={word.X}, Y={word.Y}, Width={word.Width}, Height={word.Height}"); + + if (word.Characters != null && word.Characters.Count > 0) + { + Console.WriteLine(" Characters:"); + foreach (var character in word.Characters) + { + Console.WriteLine($" Char: '{character.Value}' at X={character.X}, Y={character.Y}"); + } + } + } + Console.WriteLine(); + } + } + else + { + Console.WriteLine("No text data found in the document."); + } +} +catch (Exception e) +{ + Console.WriteLine("Exception while calling InfoApi: " + e.Message); +} +``` + +## Practical Applications + +Let's explore some practical applications of document information retrieval: + +### Creating a Document Preview + +With document information, you can generate a preview that displays basic metadata: + +```html + + + + + + Document Preview + + + +
+

Document Information

+ +
+
Format:
+
Microsoft Word Open XML Document (.docx)
+
+ +
+
Total Pages:
+
3
+
+ +
+
Page Dimensions:
+
595x841 pixels
+
+
+ +

Page Thumbnails

+
+
Page 1
+
Page 2
+
Page 3
+
+ +

Attachments

+
+
+
📄
+
No attachments found
+
+
+ + +``` + +### Planning a Document Viewer UI + +You can use document information to intelligently configure your document viewer: + +```javascript +// Example pseudo-code for a document viewer application +function configureDocumentViewer(documentInfo) { + // Set the total number of pages for pagination + viewer.setTotalPages(documentInfo.pages.length); + + // Set the initial zoom based on the page dimensions + if (documentInfo.pages.length > 0) { + const firstPage = documentInfo.pages[0]; + const aspectRatio = firstPage.width / firstPage.height; + viewer.setOptimalZoom(aspectRatio); + } + + // Configure attachments panel if needed + if (documentInfo.attachments && documentInfo.attachments.length > 0) { + viewer.showAttachmentsPanel(); + viewer.setAttachments(documentInfo.attachments); + } else { + viewer.hideAttachmentsPanel(); + } + + // Configure text selection if text coordinates are available + const hasTextData = documentInfo.pages.some(page => + page.lines && page.lines.length > 0 + ); + + if (hasTextData) { + viewer.enableTextSelection(documentInfo.pages); + } else { + viewer.disableTextSelection(); + } + + // Configure special features based on document type + if (documentInfo.pdfViewInfo) { + viewer.enablePdfFeatures(); + } + if (documentInfo.cadViewInfo) { + viewer.enableCadFeatures(); + } +} +``` + +## Try It Yourself + +Now that you've learned how to retrieve document information using GroupDocs.Viewer Cloud API, try it with different document types: + +### Exercise 1: Compare Document Types + +1. Retrieve information for different document types (PDF, DOCX, XLSX, PPTX) +2. Compare the structure and properties returned for each format +3. Note any format-specific information returned + +### Exercise 2: Implement Text Search + +1. Retrieve document information with text coordinates enabled +2. Create a simple search function that highlights matching text based on the coordinates +3. Test with different search terms + +## Troubleshooting Tips + +- Authentication Issues: Ensure your Client ID and Client Secret are correct and that you're generating a fresh JWT token +- File Not Found: Verify that the file path in your request matches the actual path in cloud storage +- Text Extraction: Text extraction is only available for certain document formats and requires setting the correct view format (PNG or JPG) +- Large Documents: For very large documents, consider retrieving information for specific pages rather than the entire document + +## What You've Learned + +In this tutorial, you've learned: +- How to retrieve comprehensive document information using GroupDocs.Viewer Cloud API +- How to extract text with coordinates for implementing text selection +- How to access information about document attachments +- How to use document information to plan and configure document viewing experiences +- How to implement these features in your applications using SDKs + +## Next Steps + +Ready to explore more document viewing capabilities? Check out these related tutorials: +- [HTML Viewer Basic Tutorial](/basic-usage/html-viewer/) +- [Image Viewer Tutorial](/basic-usage/image-viewer/) +- [PDF Viewer Tutorial](/basic-usage/pdf-viewer/) + +## Helpful Resources + +- [Product Page](https://products.groupdocs.cloud/viewer/) +- [Documentation](https://docs.groupdocs.cloud/viewer/) +- [Live Demo](https://products.groupdocs.app/viewer/family) +- [API Reference](https://reference.groupdocs.cloud/viewer/) +- [Blog](https://blog.groupdocs.cloud/categories/groupdocs.viewer-cloud-product-family/) +- [Free Support Forum](https://forum.groupdocs.cloud/c/viewer/9) +- [Free Trial](https://dashboard.groupdocs.cloud/#/apps) + +## Feedback and Questions + +Have questions about retrieving document information? Need help implementing it in your application? We welcome your feedback and questions on our [support forum](https://forum.groupdocs.cloud/c/viewer/9). \ No newline at end of file diff --git a/content/viewer/english/basic-usage/get-supported-file-formats/_index.md b/content/viewer/english/basic-usage/get-supported-file-formats/_index.md new file mode 100644 index 0000000..baa4d29 --- /dev/null +++ b/content/viewer/english/basic-usage/get-supported-file-formats/_index.md @@ -0,0 +1,683 @@ +--- +title: How to Get Supported File Formats with GroupDocs.Viewer Cloud API Tutorial +url: /basic-usage/get-supported-file-formats/ +description: Learn how to retrieve the complete list of file formats supported by GroupDocs.Viewer Cloud API in this beginner-friendly tutorial +weight: 4 +--- + +# Tutorial: How to Get Supported File Formats with GroupDocs.Viewer Cloud API + +## Learning Objectives + +In this tutorial, you'll learn how to: +- Retrieve the complete list of file formats supported by GroupDocs.Viewer Cloud API +- Understand how to check format compatibility programmatically +- Implement format validation in your applications +- Filter formats by type and category + +## Prerequisites + +Before starting this tutorial, you should have: +- A GroupDocs.Viewer Cloud account (get your [free trial here](https://dashboard.groupdocs.cloud/#/apps)) +- Your Client ID and Client Secret +- Basic understanding of REST APIs +- Familiarity with your programming language of choice (C#, Java, Python, PHP, Ruby, Node.js, or Go) + +## Why Check Supported Formats? + +Checking supported file formats is an important step in building robust document viewing applications. Understanding which file types can be processed by GroupDocs.Viewer Cloud API helps you: + +- Validate user uploads: Prevent users from uploading unsupported file types +- Plan format conversions: Determine if intermediate conversion steps are needed +- Display format options: Show users which file types they can work with +- Handle errors gracefully: Provide meaningful error messages for unsupported formats +- Optimize user experience: Set appropriate expectations for your application's capabilities + +GroupDocs.Viewer Cloud API supports over 50 file formats, including popular document types, images, CAD drawings, and more. + +## Step 1: Authenticate with the API + +Before retrieving supported formats, you need to authenticate with the API: + +```bash +# Get JSON Web Token +curl -v "https://api.groupdocs.cloud/connect/token" \ +-X POST \ +-d "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET" \ +-H "Content-Type: application/x-www-form-urlencoded" \ +-H "Accept: application/json" + +# Store JWT in a variable for reuse +JWT="YOUR_JWT_TOKEN" +``` + +## Step 2: Retrieve Supported File Formats + +Now, let's use the API to retrieve the list of supported formats: + +```bash +curl -X GET "https://api.groupdocs.cloud/v2.0/viewer/formats" \ +-H "accept: application/json" \ +-H "authorization: Bearer $JWT" +``` + +### Understanding the Response + +The API returns a comprehensive list of supported formats: + +```json +{ + "formats": [ + { + "extension": ".pdf", + "fileFormat": "Portable Document Format" + }, + { + "extension": ".doc", + "fileFormat": "Microsoft Word" + }, + { + "extension": ".docx", + "fileFormat": "Microsoft Word" + }, + { + "extension": ".xls", + "fileFormat": "Microsoft Excel" + }, + { + "extension": ".xlsx", + "fileFormat": "Microsoft Excel" + }, + // ... more formats + ] +} +``` + +Each format entry includes: +- extension: The file extension (e.g., ".pdf", ".docx") +- fileFormat: The human-readable format name (e.g., "Microsoft Word", "Portable Document Format") + +## Step 3: Implement in Your Application + +Now let's implement format retrieval in a real application using one of our supported SDKs. + +### C# Example + +```csharp +using GroupDocs.Viewer.Cloud.Sdk.Api; +using GroupDocs.Viewer.Cloud.Sdk.Client; +using System; +using System.Collections.Generic; +using System.Linq; + +namespace GroupDocs.Viewer.Cloud.Tutorial +{ + class Program + { + static void Main(string[] args) + { + // Get your client ID and client secret from https://dashboard.groupdocs.cloud/ + string MyClientId = "YOUR_CLIENT_ID"; + string MyClientSecret = "YOUR_CLIENT_SECRET"; + + // Create API instance + var configuration = new Configuration(MyClientId, MyClientSecret); + var apiInstance = new InfoApi(configuration); + + try + { + // Call the API to get supported file formats + var response = apiInstance.GetSupportedFileFormats(); + + Console.WriteLine($"Total supported formats: {response.Formats.Count}\n"); + + // Display all supported formats + Console.WriteLine("All supported formats:"); + foreach (var format in response.Formats) + { + Console.WriteLine($" {format.FileFormat} ({format.Extension})"); + } + + // Group formats by category + var formatsByCategory = response.Formats + .GroupBy(f => f.FileFormat) + .OrderBy(g => g.Key); + + Console.WriteLine("\nFormats by category:"); + foreach (var category in formatsByCategory) + { + var extensions = string.Join(", ", category.Select(f => f.Extension)); + Console.WriteLine($" {category.Key}: {extensions}"); + } + + // Get Microsoft Office formats + var officeFormats = response.Formats + .Where(f => f.FileFormat.StartsWith("Microsoft")) + .ToList(); + + Console.WriteLine("\nMicrosoft Office formats:"); + foreach (var format in officeFormats) + { + Console.WriteLine($" {format.FileFormat} ({format.Extension})"); + } + + // Check if a specific format is supported + string formatToCheck = ".docx"; + bool isSupported = response.Formats.Any(f => f.Extension.Equals(formatToCheck, StringComparison.OrdinalIgnoreCase)); + + Console.WriteLine($"\nIs {formatToCheck} supported? {isSupported}"); + } + catch (Exception e) + { + Console.WriteLine("Exception while calling InfoApi: " + e.Message); + } + + Console.WriteLine("\nPress any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +### Python Example + +```python +# Import modules +import groupdocs_viewer_cloud +from collections import defaultdict + +# Get your client ID and client secret from https://dashboard.groupdocs.cloud/ +client_id = "YOUR_CLIENT_ID" +client_secret = "YOUR_CLIENT_SECRET" + +# Create API instance +api_instance = groupdocs_viewer_cloud.InfoApi.from_keys(client_id, client_secret) + +try: + # Call the API to get supported file formats + response = api_instance.get_supported_file_formats() + + print(f"Total supported formats: {len(response.formats)}\n") + + # Display all supported formats + print("All supported formats:") + for format_info in response.formats: + print(f" {format_info.file_format} ({format_info.extension})") + + # Group formats by category + formats_by_category = defaultdict(list) + for format_info in response.formats: + formats_by_category[format_info.file_format].append(format_info.extension) + + print("\nFormats by category:") + for category, extensions in sorted(formats_by_category.items()): + print(f" {category}: {', '.join(extensions)}") + + # Get image formats + image_formats = [f for f in response.formats if f.file_format == "Image files"] + + print("\nImage formats:") + for format_info in image_formats: + print(f" {format_info.extension}") + + # Check if a specific format is supported + format_to_check = ".pptx" + is_supported = any(f.extension.lower() == format_to_check.lower() for f in response.formats) + + print(f"\nIs {format_to_check} supported? {is_supported}") + +except groupdocs_viewer_cloud.ApiException as e: + print(f"Exception while calling InfoApi: {e}") +``` + +## Step 4: Creating a Format Validator + +Let's create a utility function that validates file formats for your application: + +### C# Format Validator + +```csharp +public class FormatValidator +{ + private List _supportedExtensions; + + public FormatValidator(InfoApi api) + { + // Retrieve supported formats and store extensions + var formats = api.GetSupportedFileFormats(); + _supportedExtensions = formats.Formats + .Select(f => f.Extension.ToLowerInvariant()) + .ToList(); + } + + public bool IsFormatSupported(string filePath) + { + // Extract file extension + string extension = System.IO.Path.GetExtension(filePath).ToLowerInvariant(); + + // Check if extension is in supported list + return _supportedExtensions.Contains(extension); + } + + public List GetAllSupportedExtensions() + { + return _supportedExtensions; + } + + public List FilterByCategory(string categoryName) + { + // This would require storing the category information as well + // For simplicity, we'll return all extensions + return _supportedExtensions; + } +} + +// Usage: +var validator = new FormatValidator(apiInstance); +bool canProcess = validator.IsFormatSupported("document.docx"); +``` + +### Python Format Validator + +```python +class FormatValidator: + def __init__(self, api): + # Retrieve supported formats and store extensions + formats = api.get_supported_file_formats() + self.supported_extensions = [f.extension.lower() for f in formats.formats] + + # Create a dictionary for formats by category + self.formats_by_category = {} + for format_info in formats.formats: + category = format_info.file_format + if category not in self.formats_by_category: + self.formats_by_category[category] = [] + self.formats_by_category[category].append(format_info.extension.lower()) + + def is_format_supported(self, file_path): + # Extract file extension + import os + extension = os.path.splitext(file_path)[1].lower() + + # Check if extension is in supported list + return extension in self.supported_extensions + + def get_all_supported_extensions(self): + return self.supported_extensions + + def filter_by_category(self, category_name): + return self.formats_by_category.get(category_name, []) + +# Usage: +validator = FormatValidator(api_instance) +can_process = validator.is_format_supported("document.docx") +``` + +## Step 5: Building a Format Selection Component + +Let's create a simple HTML component that displays supported formats to users: + +```html + + + + + + Supported File Formats + + + +

Supported File Formats

+ +
+

Select Format Category

+ +
+ + + + + + + + +
+ +

Supported Formats

+
+ +
+
+ +
+

Check Your File

+

Upload a file to check if it's supported by our viewer

+ + + + +
+
+ + + + +``` + +This HTML page provides a user-friendly interface for: +- Viewing all supported formats +- Filtering formats by category +- Testing if a specific file is supported + +## Try It Yourself + +Now that you've learned how to retrieve and work with supported file formats, try these exercises: + +### Exercise 1: Create a Format Filter + +Create a utility that categorizes file formats into groups like "Documents", "Spreadsheets", "Presentations", "Images", etc. based on their descriptions. + +### Exercise 2: Build a File Upload Validator + +Create a simple web form that validates uploaded files against the list of supported formats and provides immediate feedback to users. + +### Exercise 3: Format Statistics + +Generate statistics about the supported formats, such as: +- Total number of supported formats +- Number of formats by category +- Most common file extensions + +## Practical Applications + +Let's explore some practical applications of format information: + +### Upload Component with Format Validation + +```javascript +function createUploadComponent(supportedFormats) { + // Create upload component with format validation + const component = { + validateFile: function(file) { + const fileName = file.name; + const fileExtension = '.' + fileName.split('.').pop().toLowerCase(); + + return supportedFormats.some(format => + format.extension.toLowerCase() === fileExtension + ); + }, + + getAcceptAttribute: function() { + // Generate the "accept" attribute for HTML file inputs + return supportedFormats.map(format => format.extension).join(','); + }, + + getFormatCategories: function() { + // Get unique categories + const categories = new Set(supportedFormats.map(format => format.fileFormat)); + return Array.from(categories); + }, + + getFileTypeDescription: function(fileName) { + const fileExtension = '.' + fileName.split('.').pop().toLowerCase(); + const format = supportedFormats.find(format => + format.extension.toLowerCase() === fileExtension + ); + + return format ? format.fileFormat : 'Unknown format'; + } + }; + + return component; +} + +// Usage example: +const uploadComponent = createUploadComponent(supportedFormats); +console.log('Accept attribute:', uploadComponent.getAcceptAttribute()); +console.log('Is sample.docx supported:', uploadComponent.validateFile({name: 'sample.docx'})); +console.log('File type:', uploadComponent.getFileTypeDescription('sample.xlsx')); +``` + +### File Format Documentation Generator + +```javascript +function generateFormatDocumentation(supportedFormats) { + // Group formats by category + const formatsByCategory = {}; + + supportedFormats.forEach(format => { + if (!formatsByCategory[format.fileFormat]) { + formatsByCategory[format.fileFormat] = []; + } + + formatsByCategory[format.fileFormat].push(format.extension); + }); + + // Generate documentation HTML + let html = '
'; + html += '

Supported File Formats

'; + + for (const category in formatsByCategory) { + html += `
`; + html += `

${category}

`; + html += `

Supported extensions: ${formatsByCategory[category].join(', ')}

`; + html += `
`; + } + + html += '
'; + + return html; +} + +// Usage example: +const documentationHtml = generateFormatDocumentation(supportedFormats); +document.getElementById('documentation').innerHTML = documentationHtml; +``` + +## Troubleshooting Tips + +- Authentication Issues: Ensure your Client ID and Client Secret are correct and that you're generating a fresh JWT token +- API Changes: The list of supported formats may be updated over time as new formats are added to the API +- Extension vs. Format: Remember that some file formats may share the same extension (e.g., ".xml" can be used for different types of XML-based formats) +- MIME Types: If you're working with web uploads, you might need to map extensions to MIME types + +## What You've Learned + +In this tutorial, you've learned: +- How to retrieve the complete list of file formats supported by GroupDocs.Viewer Cloud API +- How to implement format validation in your applications +- How to categorize and filter formats by type +- How to build user-friendly interfaces for format selection +- How to create utilities for working with format information + +## Next Steps + +Ready to put your knowledge into practice? Check out these related tutorials: +- [Document Information Tutorial](/basic-usage/get-document-information/) +- [HTML Viewer Basic Tutorial](/basic-usage/html-viewer/) + +## Helpful Resources + +- [Product Page](https://products.groupdocs.cloud/viewer/) +- [Documentation](https://docs.groupdocs.cloud/viewer/) +- [Live Demo](https://products.groupdocs.app/viewer/family) +- [API Reference](https://reference.groupdocs.cloud/viewer/) +- [Blog](https://blog.groupdocs.cloud/categories/groupdocs.viewer-cloud-product-family/) +- [Free Support Forum](https://forum.groupdocs.cloud/c/viewer/9) +- [Free Trial](https://dashboard.groupdocs.cloud/#/apps) + +## Feedback and Questions + +Have questions about supported file formats? Need help implementing format validation in your application? We welcome your feedback and questions on our [support forum](https://forum.groupdocs.cloud/c/viewer/9). \ No newline at end of file diff --git a/content/viewer/english/basic-usage/html-viewer-responsive-layout/_index.md b/content/viewer/english/basic-usage/html-viewer-responsive-layout/_index.md new file mode 100644 index 0000000..6162049 --- /dev/null +++ b/content/viewer/english/basic-usage/html-viewer-responsive-layout/_index.md @@ -0,0 +1,423 @@ +--- +title: Creating Responsive HTML Layout with GroupDocs.Viewer Cloud API Tutorial +description: Learn how to create responsive HTML document views that adapt to different screen sizes using GroupDocs.Viewer Cloud API in this step-by-step tutorial +url: /basic-usage/html-viewer-responsive-layout/ +weight: 6 +--- + +# Tutorial: Creating Responsive HTML Layout with GroupDocs.Viewer Cloud API + +## Learning Objectives + +In this tutorial, you'll learn how to: +- Enable responsive HTML rendering for your documents +- Create mobile-friendly document views that adapt to different screen sizes +- Implement responsive document viewing in your web applications +- Test responsive views across different devices + +## Prerequisites + +Before starting this tutorial, you should have: +- A GroupDocs.Viewer Cloud account (get your [free trial here](https://dashboard.groupdocs.cloud/#/apps)) +- Your Client ID and Client Secret +- Basic understanding of HTML and responsive web design +- A document to render (we'll use a sample DOCX document in this tutorial) + +## Understanding Responsive Document Viewing + +In today's multi-device world, responsive design is essential for providing an optimal viewing experience across a wide range of devices—from desktop computers to smartphones. When rendering documents for web viewing, the same principle applies. + +GroupDocs.Viewer Cloud API provides a simple way to make your rendered HTML documents responsive, ensuring they look great on any device without horizontal scrolling or zooming. + +### How Responsive HTML Rendering Works + +When you enable responsive rendering: +1. The API generates HTML with responsive CSS rules +2. Text and content automatically adjust to the viewport width +3. Images and other elements scale proportionally +4. The layout adapts to different screen sizes + +## Step 1: Enable Responsive Layout + +To enable responsive rendering, you need to set the `IsResponsive` property to `true` in the HTML rendering options. Let's see how to do this using cURL: + +```bash +# First get JSON Web Token +curl -v "https://api.groupdocs.cloud/connect/token" \ +-X POST \ +-d "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET" \ +-H "Content-Type: application/x-www-form-urlencoded" \ +-H "Accept: application/json" + +# Store JWT in a variable for reuse +JWT="YOUR_JWT_TOKEN" + +# Render document with responsive layout +curl -v "https://api.groupdocs.cloud/v2.0/viewer/view" \ +-X POST \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +-H "Authorization: Bearer $JWT" \ +-d "{ + 'FileInfo': { + 'FilePath': 'SampleFiles/sample.docx' + }, + 'ViewFormat': 'HTML', + 'RenderOptions': { + 'IsResponsive': true + } +}" +``` + +This API call will render your document to HTML with responsive layout enabled. + +## Step 2: Examine the Response + +After making the API call, you'll receive a response like this: + +```json +{ + "pages": [ + { + "number": 1, + "resources": null, + "path": "viewer/sample_docx/sample_page_1.html", + "downloadUrl": "https://api.groupdocs.cloud/v2.0/viewer/storage/file/viewer/sample_docx/sample_page_1.html" + }, + { + "number": 2, + "resources": null, + "path": "viewer/sample_docx/sample_page_2.html", + "downloadUrl": "https://api.groupdocs.cloud/v2.0/viewer/storage/file/viewer/sample_docx/sample_page_2.html" + }, + { + "number": 3, + "resources": null, + "path": "viewer/sample_docx/sample_page_3.html", + "downloadUrl": "https://api.groupdocs.cloud/v2.0/viewer/storage/file/viewer/sample_docx/sample_page_3.html" + } + ], + "attachments": [], + "file": null +} +``` + +## Step 3: Download and Check the Responsive HTML + +Download one of the rendered HTML pages to examine its responsive structure: + +```bash +curl -v "https://api.groupdocs.cloud/v2.0/viewer/storage/file/viewer/sample_docx/sample_page_1.html" \ +-X GET \ +-H "Authorization: Bearer $JWT" \ +--output "responsive_page1.html" +``` + +If you open the downloaded HTML file in a text editor, you'll notice that it includes responsive CSS styles. These styles ensure that the content adapts to different screen sizes. + +## Step 4: Implement in Your Application + +Now let's implement responsive HTML rendering in a real application using one of our supported SDKs. + +### C# Example + +```csharp +using GroupDocs.Viewer.Cloud.Sdk.Api; +using GroupDocs.Viewer.Cloud.Sdk.Client; +using GroupDocs.Viewer.Cloud.Sdk.Model; +using GroupDocs.Viewer.Cloud.Sdk.Model.Requests; +using System; +using System.Collections.Generic; +using System.IO; + +namespace GroupDocs.Viewer.Cloud.Tutorial +{ + class Program + { + static void Main(string[] args) + { + // Get your client ID and client secret from https://dashboard.groupdocs.cloud/ + string MyClientId = "YOUR_CLIENT_ID"; + string MyClientSecret = "YOUR_CLIENT_SECRET"; + + // Create API instance + var configuration = new Configuration(MyClientId, MyClientSecret); + var apiInstance = new ViewApi(configuration); + + // Define rendering options with responsive layout enabled + var viewOptions = new ViewOptions + { + FileInfo = new FileInfo + { + FilePath = "SampleFiles/sample.docx" + }, + ViewFormat = ViewOptions.ViewFormatEnum.HTML, + RenderOptions = new HtmlOptions + { + IsResponsive = true + } + }; + + try + { + // Call the API to render the document + var response = apiInstance.CreateView(new CreateViewRequest(viewOptions)); + + Console.WriteLine("Document rendered with responsive layout!"); + + // Print information about the rendered pages + foreach (var page in response.Pages) + { + Console.WriteLine($"Page {page.Number}: {page.DownloadUrl}"); + + // Download the rendered HTML (optional) + using (var webClient = new System.Net.WebClient()) + { + webClient.Headers.Add("Authorization", "Bearer " + configuration.GetToken()); + webClient.DownloadFile(page.DownloadUrl, $"responsive_page_{page.Number}.html"); + Console.WriteLine($"Downloaded responsive_page_{page.Number}.html"); + } + } + + Console.WriteLine("\nThe HTML files now have responsive layout enabled!"); + Console.WriteLine("Try opening them on different devices or resize your browser window to see the responsive behavior."); + } + catch (Exception e) + { + Console.WriteLine("Exception while calling ViewApi: " + e.Message); + } + + Console.WriteLine("Press any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +### Python Example + +```python +# Import modules +import os +import requests +import groupdocs_viewer_cloud + +# Get your client ID and client secret from https://dashboard.groupdocs.cloud/ +client_id = "YOUR_CLIENT_ID" +client_secret = "YOUR_CLIENT_SECRET" + +# Create API instance +api_instance = groupdocs_viewer_cloud.ViewApi.from_keys(client_id, client_secret) + +# Define rendering options with responsive layout enabled +view_options = groupdocs_viewer_cloud.ViewOptions() +view_options.file_info = groupdocs_viewer_cloud.FileInfo() +view_options.file_info.file_path = "SampleFiles/sample.docx" +view_options.view_format = "HTML" +view_options.render_options = groupdocs_viewer_cloud.HtmlOptions() +view_options.render_options.is_responsive = True + +try: + # Call the API to render the document + request = groupdocs_viewer_cloud.CreateViewRequest(view_options) + response = api_instance.create_view(request) + + print("Document rendered with responsive layout!") + + # Print information about the rendered pages + for page in response.pages: + print(f"Page {page.number}: {page.download_url}") + + # Download the rendered HTML (optional) + response = requests.get( + page.download_url, + headers={"Authorization": f"Bearer {api_instance.configuration.access_token}"} + ) + + if response.status_code == 200: + with open(f"responsive_page_{page.number}.html", "wb") as file: + file.write(response.content) + print(f"Downloaded responsive_page_{page.number}.html") + + print("\nThe HTML files now have responsive layout enabled!") + print("Try opening them on different devices or resize your browser window to see the responsive behavior.") + +except groupdocs_viewer_cloud.ApiException as e: + print(f"Exception while calling ViewApi: {e}") +``` + +## Step 5: Create a Simple Viewer Application + +Now, let's create a simple HTML viewer application that displays your responsive document. This example demonstrates how to embed the responsive HTML in a web page: + +```html + + + + + + Responsive Document Viewer + + + +
+

Responsive Document Viewer

+
+
+ +
+ +
+
+ + + + +``` + +Save this as `viewer.html` in the same directory as your downloaded responsive HTML pages. Open it in a web browser to see how your responsive document looks in a real-world application. + +## Try It Yourself + +Now that you've learned how to create responsive HTML views, try experimenting with different document types and devices. Here are some exercises to enhance your learning: + +### Exercise 1: Test Across Multiple Devices + +1. Render a multi-page document with responsive layout enabled +2. Open the rendered HTML pages on different devices (desktop, tablet, smartphone) +3. Observe how the content adapts to different screen sizes + +### Exercise 2: Compare Responsive vs. Non-Responsive + +1. Render the same document twice - once with responsive layout enabled and once without +2. Compare the HTML structure and CSS of both versions +3. Test both versions on a mobile device and note the differences + +## Troubleshooting Tips + +- Content Not Adapting: If your content doesn't seem responsive, make sure the `IsResponsive` property is set to `true` in your rendering options +- Text Overflow: Some documents with complex layouts might still have text overflow issues on very small screens - consider adding custom CSS for edge cases +- Images Not Scaling: Ensure that any custom styling you add doesn't override the responsive image settings + +## What You've Learned + +In this tutorial, you've learned: +- How to enable responsive HTML rendering in GroupDocs.Viewer Cloud API +- The benefits of responsive document viewing for multi-device support +- How to implement responsive document viewing in your applications using SDKs +- How to create a simple viewer application that displays responsive documents +- Best practices for testing responsive document views across devices + +## Helpful Resources + +- [Product Page](https://products.groupdocs.cloud/viewer/) +- [Documentation](https://docs.groupdocs.cloud/viewer/) +- [Live Demo](https://products.groupdocs.app/viewer/family) +- [API Reference](https://reference.groupdocs.cloud/viewer/) +- [Blog](https://blog.groupdocs.cloud/categories/groupdocs.viewer-cloud-product-family/) +- [Free Support Forum](https://forum.groupdocs.cloud/c/viewer/9) +- [Free Trial](https://dashboard.groupdocs.cloud/#/apps) + +## Feedback and Questions + +Have questions about responsive document viewing? Need help implementing it in your application? We welcome your feedback and questions on our [support forum](https://forum.groupdocs.cloud/c/viewer/9). \ No newline at end of file diff --git a/content/viewer/english/basic-usage/html-viewer/_index.md b/content/viewer/english/basic-usage/html-viewer/_index.md new file mode 100644 index 0000000..3154914 --- /dev/null +++ b/content/viewer/english/basic-usage/html-viewer/_index.md @@ -0,0 +1,297 @@ +--- +title: How to Use the HTML Viewer with GroupDocs.Viewer Cloud API Tutorial +description: Learn how to render documents to HTML format with this step-by-step tutorial for GroupDocs.Viewer Cloud API +url: /basic-usage/html-viewer/ +weight: 5 +--- + +# Tutorial: How to Use the HTML Viewer with GroupDocs.Viewer Cloud API + +## Learning Objectives + +In this tutorial, you'll learn how to: +- Render documents to HTML format using GroupDocs.Viewer Cloud API +- Understand the different HTML rendering options available +- Implement HTML viewing in your applications with practical examples +- Access and manipulate rendered HTML documents + +## Prerequisites + +Before starting this tutorial, you should have: +- A GroupDocs.Viewer Cloud account (get your [free trial here](https://dashboard.groupdocs.cloud/#/apps)) +- Your Client ID and Client Secret +- Basic understanding of REST APIs +- Familiarity with your programming language of choice (C#, Java, Python, PHP, Ruby, Node.js, or Go) +- A document you want to convert to HTML (we'll use a sample DOCX in this tutorial) + +## HTML Rendering Overview + +HTML rendering converts your documents to HTML format, making them viewable in any web browser without requiring special plugins or applications. GroupDocs.Viewer Cloud API makes this process seamless with powerful options to customize the output. + +### Why Convert Documents to HTML? + +Converting documents to HTML offers several advantages: +- Universal Access: HTML is supported by all modern browsers +- Responsive Design: HTML can be styled to adapt to different screen sizes +- Interactive Features: Elements can be made interactive with JavaScript +- Easy Integration: HTML can be easily embedded in web applications + +## Step 1: Upload Your Document to Cloud Storage + +Before rendering a document, you need to upload it to GroupDocs.Viewer Cloud storage. + +```bash +# First get JSON Web Token +curl -v "https://api.groupdocs.cloud/connect/token" \ +-X POST \ +-d "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET" \ +-H "Content-Type: application/x-www-form-urlencoded" \ +-H "Accept: application/json" + +# Store JWT in a variable for reuse +JWT="YOUR_JWT_TOKEN" + +# Upload file to storage +curl -v "https://api.groupdocs.cloud/v2.0/viewer/storage/file/SampleFiles/sample.docx" \ +-X PUT \ +-H "Content-Type: multipart/form-data" \ +-H "Accept: application/json" \ +-H "Authorization: Bearer $JWT" \ +--data-binary "@/path/to/your/sample.docx" +``` + +## Step 2: Render Document to HTML + +Now that your document is in cloud storage, you can render it to HTML format. + +```bash +curl -v "https://api.groupdocs.cloud/v2.0/viewer/view" \ +-X POST \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +-H "Authorization: Bearer $JWT" \ +-d "{ + 'FileInfo': { + 'FilePath': 'SampleFiles/sample.docx' + }, + 'ViewFormat': 'HTML' +}" +``` + +The API will process your document and return information about the rendered HTML pages. + +### Understanding the Response + +```json +{ + "pages": [ + { + "number": 1, + "resources": null, + "path": "viewer/sample_docx/sample_page_1.html", + "downloadUrl": "https://api.groupdocs.cloud/v2.0/viewer/storage/file/viewer/sample_docx/sample_page_1.html" + }, + { + "number": 2, + "resources": null, + "path": "viewer/sample_docx/sample_page_2.html", + "downloadUrl": "https://api.groupdocs.cloud/v2.0/viewer/storage/file/viewer/sample_docx/sample_page_2.html" + }, + ... + ], + "attachments": [], + "file": null +} +``` + +The response contains: +- An array of pages with their numbers and download URLs +- Information about any attachments (if present) +- Paths to access the rendered HTML files + +## Step 3: Download and Display the HTML Pages + +To access the rendered HTML, you can download each page using the provided URLs: + +```bash +curl -v "https://api.groupdocs.cloud/v2.0/viewer/storage/file/viewer/sample_docx/sample_page_1.html" \ +-X GET \ +-H "Authorization: Bearer $JWT" \ +--output "page1.html" +``` + +## Step 4: Implement in Your Application + +Now let's implement this process in a real application using one of our supported SDKs. + +### C# Example + +```csharp +using GroupDocs.Viewer.Cloud.Sdk.Api; +using GroupDocs.Viewer.Cloud.Sdk.Client; +using GroupDocs.Viewer.Cloud.Sdk.Model; +using GroupDocs.Viewer.Cloud.Sdk.Model.Requests; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; + +namespace GroupDocs.Viewer.Cloud.Tutorial +{ + class Program + { + static void Main(string[] args) + { + // Get your client ID and client secret from https://dashboard.groupdocs.cloud/ + string MyClientId = "YOUR_CLIENT_ID"; + string MyClientSecret = "YOUR_CLIENT_SECRET"; + + // Create API instance + var configuration = new Configuration(MyClientId, MyClientSecret); + var apiInstance = new ViewApi(configuration); + + // Define rendering options + var viewOptions = new ViewOptions + { + FileInfo = new FileInfo + { + FilePath = "SampleFiles/sample.docx" + }, + ViewFormat = ViewOptions.ViewFormatEnum.HTML + }; + + try + { + // Call the API to render the document + var response = apiInstance.CreateView(new CreateViewRequest(viewOptions)); + + Console.WriteLine("Document rendered successfully!"); + + // Print information about the rendered pages + foreach (var page in response.Pages) + { + Console.WriteLine($"Page {page.Number}: {page.DownloadUrl}"); + + // Download the rendered HTML (optional) + using (var webClient = new System.Net.WebClient()) + { + webClient.Headers.Add("Authorization", "Bearer " + configuration.GetToken()); + webClient.DownloadFile(page.DownloadUrl, $"page_{page.Number}.html"); + } + } + + // Open the first page in default browser + if (response.Pages.Count > 0) + { + Process.Start(new ProcessStartInfo + { + FileName = $"page_1.html", + UseShellExecute = true + }); + } + } + catch (Exception e) + { + Console.WriteLine("Exception while calling ViewApi: " + e.Message); + } + + Console.WriteLine("Press any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +### Python Example + +```python +# Import modules +import os +import webbrowser +import requests +import groupdocs_viewer_cloud + +# Get your client ID and client secret from https://dashboard.groupdocs.cloud/ +client_id = "YOUR_CLIENT_ID" +client_secret = "YOUR_CLIENT_SECRET" + +# Create API instance +api_instance = groupdocs_viewer_cloud.ViewApi.from_keys(client_id, client_secret) + +# Define rendering options +view_options = groupdocs_viewer_cloud.ViewOptions() +view_options.file_info = groupdocs_viewer_cloud.FileInfo() +view_options.file_info.file_path = "SampleFiles/sample.docx" +view_options.view_format = "HTML" + +try: + # Call the API to render the document + request = groupdocs_viewer_cloud.CreateViewRequest(view_options) + response = api_instance.create_view(request) + + print("Document rendered successfully!") + + # Print information about the rendered pages + for page in response.pages: + print(f"Page {page.number}: {page.download_url}") + + # Download the rendered HTML (optional) + response = requests.get( + page.download_url, + headers={"Authorization": f"Bearer {api_instance.configuration.access_token}"} + ) + + if response.status_code == 200: + with open(f"page_{page.number}.html", "wb") as file: + file.write(response.content) + print(f"Downloaded page_{page.number}.html") + + # Open the first page in default browser + if response.pages and len(response.pages) > 0: + first_page_path = os.path.abspath(f"page_1.html") + print(f"Opening {first_page_path} in browser") + webbrowser.open(f'file://{first_page_path}') + +except groupdocs_viewer_cloud.ApiException as e: + print(f"Exception while calling ViewApi: {e}") +``` + +## Try It Yourself + +Now that you've seen how to render documents to HTML using GroupDocs.Viewer Cloud API, try it with your own documents. Experiment with different file types like PDFs, Excel spreadsheets, PowerPoint presentations, or images. + +### Exercise: Customize HTML Output + +Try to modify the examples above to: +1. Render only specific pages of a document +2. Enable responsive layout +3. Exclude certain fonts from the HTML output + +## Troubleshooting Tips + +- Authentication Issues: Ensure your Client ID and Client Secret are correct and that you're generating a fresh JWT token +- File Not Found: Verify that the file path in your request matches the actual path in cloud storage +- Rendering Errors: Some complex documents may have specific rendering requirements - check the error messages for details + +## What You've Learned + +In this tutorial, you've learned: +- How to authenticate with the GroupDocs.Viewer Cloud API +- How to upload documents to cloud storage +- How to render documents to HTML format +- How to download and display the rendered HTML pages +- How to implement this functionality in your applications using SDKs + +## Helpful Resources + +- [Product Page](https://products.groupdocs.cloud/viewer/) +- [Documentation](https://docs.groupdocs.cloud/viewer/) +- [Live Demo](https://products.groupdocs.app/viewer/family) +- [API Reference](https://reference.groupdocs.cloud/viewer/) +- [Blog](https://blog.groupdocs.cloud/categories/groupdocs.viewer-cloud-product-family/) +- [Free Support Forum](https://forum.groupdocs.cloud/c/viewer/9) +- [Free Trial](https://dashboard.groupdocs.cloud/#/apps) + +## Feedback and Questions + +Have questions about this tutorial? Need help implementing HTML viewing in your application? We welcome your feedback and questions on our [support forum](https://forum.groupdocs.cloud/c/viewer/9). diff --git a/content/viewer/english/basic-usage/image-viewer/_index.md b/content/viewer/english/basic-usage/image-viewer/_index.md new file mode 100644 index 0000000..f11bef4 --- /dev/null +++ b/content/viewer/english/basic-usage/image-viewer/_index.md @@ -0,0 +1,625 @@ +--- +title: How to Use the Image Viewer with GroupDocs.Viewer Cloud API Tutorial +description: Learn how to render documents to image formats like JPG and PNG with this comprehensive tutorial for GroupDocs.Viewer Cloud API +url: /basic-usage/image-viewer/ +weight: 7 +--- + +# Tutorial: How to Use the Image Viewer with GroupDocs.Viewer Cloud API + +## Learning Objectives + +In this tutorial, you'll learn how to: +- Render documents to image formats (JPG and PNG) using GroupDocs.Viewer Cloud API +- Configure image rendering options for optimal output +- Control image quality, dimensions, and other properties +- Implement image viewing functionality in your applications +- Work with rendered image files + +## Prerequisites + +Before starting this tutorial, you should have: +- A GroupDocs.Viewer Cloud account (get your [free trial here](https://dashboard.groupdocs.cloud/#/apps)) +- Your Client ID and Client Secret +- Basic understanding of REST APIs +- Familiarity with your programming language of choice (C#, Java, Python, PHP, Ruby, Node.js, or Go) +- A document you want to convert to images (we'll use a sample DOCX in this tutorial) + +## Image Rendering Overview + +Converting documents to images (JPG, PNG) provides several advantages in various scenarios: + +- Universal Compatibility: Images can be displayed on any device without special viewers +- Static Content: Images represent an exact visual snapshot of your documents +- Simplified Integration: Images are easily integrated into websites and applications +- No Client-Side Rendering: Images don't require client-side processing to display +- Control Over Quality: You can balance image quality against file size + +GroupDocs.Viewer Cloud API makes it simple to convert documents to high-quality images with customizable options to meet your specific requirements. + +## Step 1: Upload Your Document to Cloud Storage + +Before rendering a document, you need to upload it to GroupDocs.Viewer Cloud storage. + +```bash +# First get JSON Web Token +curl -v "https://api.groupdocs.cloud/connect/token" \ +-X POST \ +-d "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET" \ +-H "Content-Type: application/x-www-form-urlencoded" \ +-H "Accept: application/json" + +# Store JWT in a variable for reuse +JWT="YOUR_JWT_TOKEN" + +# Upload file to storage +curl -v "https://api.groupdocs.cloud/v2.0/viewer/storage/file/SampleFiles/sample.docx" \ +-X PUT \ +-H "Content-Type: multipart/form-data" \ +-H "Accept: application/json" \ +-H "Authorization: Bearer $JWT" \ +--data-binary "@/path/to/your/sample.docx" +``` + +## Step 2: Render Document to JPG Images + +Now that your document is in cloud storage, you can render it to JPG format. + +```bash +curl -v "https://api.groupdocs.cloud/v2.0/viewer/view" \ +-X POST \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +-H "Authorization: Bearer $JWT" \ +-d "{ + 'FileInfo': { + 'FilePath': 'SampleFiles/sample.docx' + }, + 'ViewFormat': 'JPG' +}" +``` + +The API will process your document and return information about the rendered image files. + +### Understanding the Response + +```json +{ + "pages": [ + { + "number": 1, + "resources": null, + "path": "viewer/sample_docx/sample_page_1.jpg", + "downloadUrl": "https://api.groupdocs.cloud/v2.0/viewer/storage/file/viewer/sample_docx/sample_page_1.jpg" + }, + { + "number": 2, + "resources": null, + "path": "viewer/sample_docx/sample_page_2.jpg", + "downloadUrl": "https://api.groupdocs.cloud/v2.0/viewer/storage/file/viewer/sample_docx/sample_page_2.jpg" + }, + { + "number": 3, + "resources": null, + "path": "viewer/sample_docx/sample_page_3.jpg", + "downloadUrl": "https://api.groupdocs.cloud/v2.0/viewer/storage/file/viewer/sample_docx/sample_page_3.jpg" + } + ], + "attachments": [], + "file": null +} +``` + +The response contains: +- An array of pages with their numbers and download URLs +- Each page of the document is rendered as a separate JPG image +- Paths to access the rendered image files + +## Step 3: Download and Use the Image Files + +To access the rendered images, you can download each page using the provided URLs: + +```bash +curl -v "https://api.groupdocs.cloud/v2.0/viewer/storage/file/viewer/sample_docx/sample_page_1.jpg" \ +-X GET \ +-H "Authorization: Bearer $JWT" \ +--output "page1.jpg" +``` + +## Step 4: Rendering to PNG Format + +If you prefer PNG format (which supports transparency and offers lossless compression), simply change the `ViewFormat` parameter: + +```bash +curl -v "https://api.groupdocs.cloud/v2.0/viewer/view" \ +-X POST \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +-H "Authorization: Bearer $JWT" \ +-d "{ + 'FileInfo': { + 'FilePath': 'SampleFiles/sample.docx' + }, + 'ViewFormat': 'PNG' +}" +``` + +## Step 5: Customizing Image Output + +GroupDocs.Viewer Cloud offers several options to customize the rendered images: + +### Adjusting Image Quality + +For JPG format, you can control the quality (1-100) to balance image quality against file size: + +```bash +curl -v "https://api.groupdocs.cloud/v2.0/viewer/view" \ +-X POST \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +-H "Authorization: Bearer $JWT" \ +-d "{ + 'FileInfo': { + 'FilePath': 'SampleFiles/sample.docx' + }, + 'ViewFormat': 'JPG', + 'RenderOptions': { + 'JpegQuality': 75 + } +}" +``` + +### Setting Image Dimensions + +You can specify the width and height of the output images: + +```bash +curl -v "https://api.groupdocs.cloud/v2.0/viewer/view" \ +-X POST \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +-H "Authorization: Bearer $JWT" \ +-d "{ + 'FileInfo': { + 'FilePath': 'SampleFiles/sample.docx' + }, + 'ViewFormat': 'JPG', + 'RenderOptions': { + 'Width': 800, + 'Height': 1000 + } +}" +``` + +## Step 6: Implement in Your Application + +Now let's implement image rendering in a real application using one of our supported SDKs. + +### C# Example + +```csharp +using GroupDocs.Viewer.Cloud.Sdk.Api; +using GroupDocs.Viewer.Cloud.Sdk.Client; +using GroupDocs.Viewer.Cloud.Sdk.Model; +using GroupDocs.Viewer.Cloud.Sdk.Model.Requests; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; + +namespace GroupDocs.Viewer.Cloud.Tutorial +{ + class Program + { + static void Main(string[] args) + { + // Get your client ID and client secret from https://dashboard.groupdocs.cloud/ + string MyClientId = "YOUR_CLIENT_ID"; + string MyClientSecret = "YOUR_CLIENT_SECRET"; + + // Create API instance + var configuration = new Configuration(MyClientId, MyClientSecret); + var apiInstance = new ViewApi(configuration); + + // Define rendering options + var viewOptions = new ViewOptions + { + FileInfo = new FileInfo + { + FilePath = "SampleFiles/sample.docx" + }, + ViewFormat = ViewOptions.ViewFormatEnum.JPG, + RenderOptions = new ImageOptions + { + JpegQuality = 90, + Width = 800, + Height = 1000 + } + }; + + try + { + // Call the API to render the document + var response = apiInstance.CreateView(new CreateViewRequest(viewOptions)); + + Console.WriteLine("Document rendered to images successfully!"); + + // Create a directory to store the images + Directory.CreateDirectory("rendered_images"); + + // Download each rendered image + foreach (var page in response.Pages) + { + Console.WriteLine($"Page {page.Number}: {page.DownloadUrl}"); + + using (var webClient = new System.Net.WebClient()) + { + webClient.Headers.Add("Authorization", "Bearer " + configuration.GetToken()); + string outputPath = Path.Combine("rendered_images", $"page_{page.Number}.jpg"); + webClient.DownloadFile(page.DownloadUrl, outputPath); + Console.WriteLine($"Downloaded {outputPath}"); + } + } + + // Open the directory with rendered images + Process.Start(new ProcessStartInfo + { + FileName = "rendered_images", + UseShellExecute = true + }); + } + catch (Exception e) + { + Console.WriteLine("Exception while calling ViewApi: " + e.Message); + } + + Console.WriteLine("Press any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +### Python Example + +```python +# Import modules +import os +import requests +import groupdocs_viewer_cloud + +# Get your client ID and client secret from https://dashboard.groupdocs.cloud/ +client_id = "YOUR_CLIENT_ID" +client_secret = "YOUR_CLIENT_SECRET" + +# Create API instance +api_instance = groupdocs_viewer_cloud.ViewApi.from_keys(client_id, client_secret) + +# Define rendering options +view_options = groupdocs_viewer_cloud.ViewOptions() +view_options.file_info = groupdocs_viewer_cloud.FileInfo() +view_options.file_info.file_path = "SampleFiles/sample.docx" +view_options.view_format = "JPG" +view_options.render_options = groupdocs_viewer_cloud.ImageOptions() +view_options.render_options.jpeg_quality = 90 +view_options.render_options.width = 800 +view_options.render_options.height = 1000 + +try: + # Call the API to render the document + request = groupdocs_viewer_cloud.CreateViewRequest(view_options) + response = api_instance.create_view(request) + + print("Document rendered to images successfully!") + + # Create a directory to store the images + os.makedirs("rendered_images", exist_ok=True) + + # Download each rendered image + for page in response.pages: + print(f"Page {page.number}: {page.download_url}") + + image_response = requests.get( + page.download_url, + headers={"Authorization": f"Bearer {api_instance.configuration.access_token}"} + ) + + if image_response.status_code == 200: + output_path = os.path.join("rendered_images", f"page_{page.number}.jpg") + with open(output_path, "wb") as file: + file.write(image_response.content) + print(f"Downloaded {output_path}") + + print(f"\nAll images have been downloaded to the 'rendered_images' directory.") + + # Open the first image in default image viewer + first_image_path = os.path.abspath(os.path.join("rendered_images", "page_1.jpg")) + print(f"Opening {first_image_path}") + + import webbrowser + webbrowser.open(f'file://{first_image_path}') + +except groupdocs_viewer_cloud.ApiException as e: + print(f"Exception while calling ViewApi: {e}") +``` + +## Step 7: Creating a Simple Image Gallery + +Let's create a simple HTML gallery to display the rendered images: + +```html + + + + + + Document Image Gallery + + + +

Document Image Gallery

+ + + + + + + + +``` + +Save this as `gallery.html` in the same directory as your downloaded images. Open it in a web browser to see your rendered document pages displayed in a responsive gallery with navigation. + +## Try It Yourself + +Now that you've learned how to render documents to images using GroupDocs.Viewer Cloud API, try it with your own documents. Experiment with different file types and image rendering options. + +### Exercise: Optimize Image Quality vs. Size + +Try to find the optimal balance between image quality and file size: +1. Render the same document multiple times with different JPEG quality settings (e.g., 50, 70, 90) +2. Compare the file sizes and visual quality of the resulting images +3. Determine the optimal setting for your specific use case + +## Advanced Image Features + +GroupDocs.Viewer Cloud API offers several advanced image rendering features: + +### Text Extraction with Coordinates + +You can extract text with coordinates from the rendered images, which is useful for implementing text selection or search functionality: + +```csharp +var viewOptions = new ViewOptions +{ + FileInfo = new FileInfo + { + FilePath = "SampleFiles/sample.docx" + }, + ViewFormat = ViewOptions.ViewFormatEnum.PNG, + RenderOptions = new ImageOptions + { + ExtractText = true + } +}; +``` + +### Watermarking + +You can add text watermarks to the rendered images: + +```csharp +var viewOptions = new ViewOptions +{ + FileInfo = new FileInfo + { + FilePath = "SampleFiles/sample.docx" + }, + ViewFormat = ViewOptions.ViewFormatEnum.JPG, + RenderOptions = new ImageOptions + { + Watermark = new Watermark + { + Text = "CONFIDENTIAL", + Color = "#FF0000", + Position = Watermark.PositionEnum.Diagonal, + Size = Watermark.SizeEnum.Full + } + } +}; +``` + +## Troubleshooting Tips + +- Image Quality Issues: If images appear blurry or low-quality, try increasing the JPEG quality setting or switch to PNG format +- File Size Concerns: For large documents, consider optimizing JPEG quality or rendering only specific pages +- Memory Limitations: When processing very large documents or high-resolution images, be aware of memory usage in your application + +## What You've Learned + +In this tutorial, you've learned: +- How to render documents to JPG and PNG image formats +- How to customize image properties like quality and dimensions +- How to download and use the rendered images +- How to implement image rendering in your applications using SDKs +- How to create a simple image gallery to display rendered document pages + +## Helpful Resources + +- [Product Page](https://products.groupdocs.cloud/viewer/) +- [Documentation](https://docs.groupdocs.cloud/viewer/) +- [Live Demo](https://products.groupdocs.app/viewer/family) +- [API Reference](https://reference.groupdocs.cloud/viewer/) +- [Blog](https://blog.groupdocs.cloud/categories/groupdocs.viewer-cloud-product-family/) +- [Free Support Forum](https://forum.groupdocs.cloud/c/viewer/9) +- [Free Trial](https://dashboard.groupdocs.cloud/#/apps) + +## Feedback and Questions + +Have questions about image rendering? Need help implementing it in your application? We welcome your feedback and questions on our [support forum](https://forum.groupdocs.cloud/c/viewer/9). diff --git a/content/viewer/english/basic-usage/pdf-viewer-protect/_index.md b/content/viewer/english/basic-usage/pdf-viewer-protect/_index.md new file mode 100644 index 0000000..35aa726 --- /dev/null +++ b/content/viewer/english/basic-usage/pdf-viewer-protect/_index.md @@ -0,0 +1,404 @@ +--- +title: How to Secure PDF Documents with GroupDocs.Viewer Cloud API Tutorial +description: Learn how to implement PDF security features including passwords and permissions using GroupDocs.Viewer Cloud API in this step-by-step tutorial +url: /basic-usage/pdf-viewer-protect/ +weight: 9 +--- + +# Tutorial: How to Secure PDF Documents with GroupDocs.Viewer Cloud API + +## Learning Objectives + +In this tutorial, you'll learn how to: +- Implement password protection for PDF documents +- Set document permissions to control what users can do with your PDFs +- Configure different levels of security for different use cases +- Apply these security features using the GroupDocs.Viewer Cloud API + +## Prerequisites + +Before starting this tutorial, you should have: +- A GroupDocs.Viewer Cloud account (get your [free trial here](https://dashboard.groupdocs.cloud/#/apps)) +- Your Client ID and Client Secret +- Basic understanding of PDF security concepts +- A document to convert to a secured PDF (we'll use a sample DOCX in this tutorial) + +## Understanding PDF Security + +PDF security is essential in many business scenarios, such as: +- Sharing confidential documents +- Distributing content with usage restrictions +- Protecting intellectual property +- Complying with data protection regulations + +GroupDocs.Viewer Cloud API allows you to implement two primary security features when rendering documents to PDF: + +1. Document Open Password - Requires users to enter a password before they can open the document +2. Permissions Password - Allows you to set restrictions on what users can do with the document once opened, such as printing, copying text, or modifying + +## Step 1: Setting Up PDF Security + +To implement PDF security, you need to configure the appropriate options when rendering a document to PDF. Let's start with a simple cURL example: + +```bash +# First get JSON Web Token +curl -v "https://api.groupdocs.cloud/connect/token" \ +-X POST \ +-d "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET" \ +-H "Content-Type: application/x-www-form-urlencoded" \ +-H "Accept: application/json" + +# Store JWT in a variable for reuse +JWT="YOUR_JWT_TOKEN" + +# Render document with security settings +curl -v "https://api.groupdocs.cloud/v2.0/viewer/view" \ +-X POST \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +-H "Authorization: Bearer $JWT" \ +-d "{ + 'FileInfo': { + 'FilePath': 'SampleFiles/sample.docx' + }, + 'ViewFormat': 'PDF', + 'RenderOptions': { + 'Permissions': ['DenyModification'], + 'PermissionsPassword': 'p123', + 'DocumentOpenPassword': 'o123' + } +}" +``` + +In this example: +- `DocumentOpenPassword` sets a password that users must enter to open the document +- `PermissionsPassword` sets a password for changing permissions +- `Permissions` specifies which actions to restrict (in this case, document modification) + +## Step 2: Understanding Available Permissions + +GroupDocs.Viewer Cloud API supports the following permission settings: + +| Permission Value | Description | +|------------------|-------------| +| `AllowAll` | Allows all operations | +| `DenyPrinting` | Prevents users from printing the document | +| `DenyModification` | Prevents users from modifying the document | +| `DenyContentCopy` | Prevents users from copying content | +| `DenyFormFilling` | Prevents users from filling forms | +| `DenyScreenReaders` | Prevents screen readers from reading the document | +| `DenyAssembly` | Prevents users from assembling the document | +| `DenyDegradedPrinting` | Prevents low-quality printing | + +You can combine multiple permissions in your request: + +```json +"Permissions": ["DenyPrinting", "DenyModification", "DenyContentCopy"] +``` + +## Step 3: Download and Test Your Secured PDF + +After rendering the document, you'll receive a response like this: + +```json +{ + "pages": null, + "attachments": [], + "file": { + "path": "viewer/sample_docx/sample.pdf", + "downloadUrl": "https://api.groupdocs.cloud/v2.0/viewer/storage/file/viewer/sample_docx/sample.pdf" + } +} +``` + +Download the secured PDF to test the security features: + +```bash +curl -v "https://api.groupdocs.cloud/v2.0/viewer/storage/file/viewer/sample_docx/sample.pdf" \ +-X GET \ +-H "Authorization: Bearer $JWT" \ +--output "secured_document.pdf" +``` + +Open the PDF in any PDF reader. You should be prompted for the document open password ("o123" in our example). After opening, try to modify the document - you should find that the operation is restricted. + +## Step 4: Implement in Your Application + +Now let's implement PDF security in a real application using one of our supported SDKs. + +### C# Example + +```csharp +using GroupDocs.Viewer.Cloud.Sdk.Api; +using GroupDocs.Viewer.Cloud.Sdk.Client; +using GroupDocs.Viewer.Cloud.Sdk.Model; +using GroupDocs.Viewer.Cloud.Sdk.Model.Requests; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; + +namespace GroupDocs.Viewer.Cloud.Tutorial +{ + class Program + { + static void Main(string[] args) + { + // Get your client ID and client secret from https://dashboard.groupdocs.cloud/ + string MyClientId = "YOUR_CLIENT_ID"; + string MyClientSecret = "YOUR_CLIENT_SECRET"; + + // Create API instance + var configuration = new Configuration(MyClientId, MyClientSecret); + var apiInstance = new ViewApi(configuration); + + // Define rendering options with security settings + var viewOptions = new ViewOptions + { + FileInfo = new FileInfo + { + FilePath = "SampleFiles/sample.docx" + }, + ViewFormat = ViewOptions.ViewFormatEnum.PDF, + RenderOptions = new PdfOptions + { + Permissions = new List { "DenyModification", "DenyPrinting" }, + PermissionsPassword = "p123", + DocumentOpenPassword = "o123" + } + }; + + try + { + // Call the API to render the document + var response = apiInstance.CreateView(new CreateViewRequest(viewOptions)); + + Console.WriteLine("Document rendered with security settings!"); + Console.WriteLine($"PDF file path: {response.File.Path}"); + Console.WriteLine($"Download URL: {response.File.DownloadUrl}"); + + // Download the secured PDF (optional) + using (var webClient = new System.Net.WebClient()) + { + webClient.Headers.Add("Authorization", "Bearer " + configuration.GetToken()); + webClient.DownloadFile(response.File.DownloadUrl, "secured_document.pdf"); + Console.WriteLine("Secured PDF downloaded as secured_document.pdf"); + } + + Console.WriteLine("\nSecurity settings applied:"); + Console.WriteLine("- Document open password: o123"); + Console.WriteLine("- Permissions password: p123"); + Console.WriteLine("- Restricted actions: Modification, Printing"); + + // Open the PDF in default viewer + Process.Start(new ProcessStartInfo + { + FileName = "secured_document.pdf", + UseShellExecute = true + }); + } + catch (Exception e) + { + Console.WriteLine("Exception while calling ViewApi: " + e.Message); + } + + Console.WriteLine("Press any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +### Python Example + +```python +# Import modules +import os +import webbrowser +import requests +import groupdocs_viewer_cloud + +# Get your client ID and client secret from https://dashboard.groupdocs.cloud/ +client_id = "YOUR_CLIENT_ID" +client_secret = "YOUR_CLIENT_SECRET" + +# Create API instance +api_instance = groupdocs_viewer_cloud.ViewApi.from_keys(client_id, client_secret) + +# Define rendering options with security settings +view_options = groupdocs_viewer_cloud.ViewOptions() +view_options.file_info = groupdocs_viewer_cloud.FileInfo() +view_options.file_info.file_path = "SampleFiles/sample.docx" +view_options.view_format = "PDF" +view_options.render_options = groupdocs_viewer_cloud.PdfOptions() +view_options.render_options.permissions = ["DenyModification", "DenyPrinting"] +view_options.render_options.permissions_password = "p123" +view_options.render_options.document_open_password = "o123" + +try: + # Call the API to render the document + request = groupdocs_viewer_cloud.CreateViewRequest(view_options) + response = api_instance.create_view(request) + + print("Document rendered with security settings!") + print(f"PDF file path: {response.file.path}") + print(f"Download URL: {response.file.download_url}") + + # Download the secured PDF (optional) + pdf_response = requests.get( + response.file.download_url, + headers={"Authorization": f"Bearer {api_instance.configuration.access_token}"} + ) + + if pdf_response.status_code == 200: + with open("secured_document.pdf", "wb") as file: + file.write(pdf_response.content) + print("Secured PDF downloaded as secured_document.pdf") + + print("\nSecurity settings applied:") + print("- Document open password: o123") + print("- Permissions password: p123") + print("- Restricted actions: Modification, Printing") + + # Open the PDF in default viewer + pdf_path = os.path.abspath("secured_document.pdf") + print(f"Opening {pdf_path} in default PDF viewer") + webbrowser.open(f'file://{pdf_path}') + +except groupdocs_viewer_cloud.ApiException as e: + print(f"Exception while calling ViewApi: {e}") +``` + +## Common Security Scenarios + +Let's explore some common PDF security scenarios and how to implement them: + +### Scenario 1: Confidential Document (Open Password Only) + +Use this when you want to restrict who can open the document, but allow full access once opened: + +```csharp +var viewOptions = new ViewOptions +{ + FileInfo = new FileInfo + { + FilePath = "SampleFiles/confidential.docx" + }, + ViewFormat = ViewOptions.ViewFormatEnum.PDF, + RenderOptions = new PdfOptions + { + DocumentOpenPassword = "secret123" + } +}; +``` + +### Scenario 2: Read-Only Document (No Modifications) + +Use this when you want anyone to open the document, but prevent editing: + +```csharp +var viewOptions = new ViewOptions +{ + FileInfo = new FileInfo + { + FilePath = "SampleFiles/contract.docx" + }, + ViewFormat = ViewOptions.ViewFormatEnum.PDF, + RenderOptions = new PdfOptions + { + Permissions = new List { "DenyModification" }, + PermissionsPassword = "admin123" + } +}; +``` + +### Scenario 3: Copyright Protected Content (No Copying) + +Use this when you want to prevent copying of content: + +```csharp +var viewOptions = new ViewOptions +{ + FileInfo = new FileInfo + { + FilePath = "SampleFiles/copyrighted.docx" + }, + ViewFormat = ViewOptions.ViewFormatEnum.PDF, + RenderOptions = new PdfOptions + { + Permissions = new List { "DenyContentCopy" }, + PermissionsPassword = "admin123" + } +}; +``` + +### Scenario 4: Maximum Security (All Restrictions) + +Use this when you need maximum security: + +```csharp +var viewOptions = new ViewOptions +{ + FileInfo = new FileInfo + { + FilePath = "SampleFiles/topsecret.docx" + }, + ViewFormat = ViewOptions.ViewFormatEnum.PDF, + RenderOptions = new PdfOptions + { + DocumentOpenPassword = "open123", + Permissions = new List { + "DenyPrinting", + "DenyModification", + "DenyContentCopy", + "DenyFormFilling", + "DenyScreenReaders", + "DenyAssembly" + }, + PermissionsPassword = "admin456" + } +}; +``` + +## Try It Yourself + +Now that you've learned how to secure PDFs using GroupDocs.Viewer Cloud API, try implementing different security configurations for your own documents. + +### Exercise: Create a Document with Custom Security Settings + +1. Render a document to PDF with custom security settings based on your requirements +2. Test the PDF in different PDF readers to ensure the security settings work as expected +3. Try implementing different combinations of permission restrictions + +## Troubleshooting Tips + +- Password Not Working: Ensure you're using the correct password and that it's properly encoded in your API request +- Permissions Not Applied: Check that you're using the correct permission values and that the PDF reader you're using supports the restrictions +- API Errors: Verify that your Client ID and Client Secret are correct and that you have permission to access the document + +## What You've Learned + +In this tutorial, you've learned: +- How to implement password protection for PDF documents +- How to set document permissions to restrict what users can do with your PDFs +- How to configure different security scenarios for various use cases +- How to implement PDF security in your applications using SDKs + +## Next Steps + +Ready to explore more PDF functionality? Check out these related tutorial: +- [PDF Viewer Basic Tutorial](/basic-usage/pdf-viewer/) + +## Helpful Resources + +- [Product Page](https://products.groupdocs.cloud/viewer/) +- [Documentation](https://docs.groupdocs.cloud/viewer/) +- [Live Demo](https://products.groupdocs.app/viewer/family) +- [API Reference](https://reference.groupdocs.cloud/viewer/) +- [Blog](https://blog.groupdocs.cloud/categories/groupdocs.viewer-cloud-product-family/) +- [Free Support Forum](https://forum.groupdocs.cloud/c/viewer/9) +- [Free Trial](https://dashboard.groupdocs.cloud/#/apps) + +## Feedback and Questions + +Have questions about PDF security? Need help implementing it in your application? We welcome your feedback and questions on our [support forum](https://forum.groupdocs.cloud/c/viewer/9). diff --git a/content/viewer/english/basic-usage/pdf-viewer/_index.md b/content/viewer/english/basic-usage/pdf-viewer/_index.md new file mode 100644 index 0000000..2d15fa4 --- /dev/null +++ b/content/viewer/english/basic-usage/pdf-viewer/_index.md @@ -0,0 +1,328 @@ +--- +title: How to Use the PDF Viewer with GroupDocs.Viewer Cloud API Tutorial +description: Learn how to render documents to PDF format with this comprehensive tutorial for GroupDocs.Viewer Cloud API +url: /basic-usage/pdf-viewer/ +weight: 8 +--- + +# Tutorial: How to Use the PDF Viewer with GroupDocs.Viewer Cloud API + +## Learning Objectives + +In this tutorial, you'll learn how to: +- Render various document formats to PDF using GroupDocs.Viewer Cloud API +- Configure PDF rendering options for optimal output +- Implement PDF viewing functionality in your applications +- Work with the rendered PDF documents + +## Prerequisites + +Before starting this tutorial, you should have: +- A GroupDocs.Viewer Cloud account (get your [free trial here](https://dashboard.groupdocs.cloud/#/apps)) +- Your Client ID and Client Secret +- Basic understanding of REST APIs +- Familiarity with your programming language of choice (C#, Java, Python, PHP, Ruby, Node.js, or Go) +- A document you want to convert to PDF (we'll use a sample DOCX in this tutorial) + +## PDF Rendering Overview + +PDF (Portable Document Format) is one of the most widely used document formats for sharing and viewing documents. Converting documents to PDF offers several advantages: + +- Consistency: PDFs maintain their layout and formatting across different devices and platforms +- Security: PDFs can be protected with passwords and permissions +- Compression: PDFs can be optimized for size without significant quality loss +- Universal Support: PDF readers are available on virtually all platforms + +GroupDocs.Viewer Cloud API simplifies the process of converting various document formats to PDF, providing a consistent viewing experience for your users. + +## Step 1: Upload Your Document to Cloud Storage + +Before rendering a document, you need to upload it to GroupDocs.Viewer Cloud storage. + +```bash +# First get JSON Web Token +curl -v "https://api.groupdocs.cloud/connect/token" \ +-X POST \ +-d "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET" \ +-H "Content-Type: application/x-www-form-urlencoded" \ +-H "Accept: application/json" + +# Store JWT in a variable for reuse +JWT="YOUR_JWT_TOKEN" + +# Upload file to storage +curl -v "https://api.groupdocs.cloud/v2.0/viewer/storage/file/SampleFiles/sample.docx" \ +-X PUT \ +-H "Content-Type: multipart/form-data" \ +-H "Accept: application/json" \ +-H "Authorization: Bearer $JWT" \ +--data-binary "@/path/to/your/sample.docx" +``` + +## Step 2: Render Document to PDF + +Now that your document is in cloud storage, you can render it to PDF format. + +```bash +curl -v "https://api.groupdocs.cloud/v2.0/viewer/view" \ +-X POST \ +-H "Content-Type: application/json" \ +-H "Accept: application/json" \ +-H "Authorization: Bearer $JWT" \ +-d "{ + 'FileInfo': { + 'FilePath': 'SampleFiles/sample.docx' + }, + 'ViewFormat': 'PDF' +}" +``` + +The API will process your document and return information about the rendered PDF file. + +### Understanding the Response + +```json +{ + "pages": null, + "attachments": [], + "file": { + "path": "viewer/sample_docx/sample.pdf", + "downloadUrl": "https://api.groupdocs.cloud/v2.0/viewer/storage/file/viewer/sample_docx/sample.pdf" + } +} +``` + +The response contains: +- Information about the rendered PDF file, including its path and download URL +- Unlike HTML or image formats which return individual pages, PDF rendering returns a single file containing all pages + +## Step 3: Download the PDF File + +To access the rendered PDF, you can download it using the provided URL: + +```bash +curl -v "https://api.groupdocs.cloud/v2.0/viewer/storage/file/viewer/sample_docx/sample.pdf" \ +-X GET \ +-H "Authorization: Bearer $JWT" \ +--output "rendered_document.pdf" +``` + +## Step 4: Implement in Your Application + +Now let's implement this process in a real application using one of our supported SDKs. + +### C# Example + +```csharp +using GroupDocs.Viewer.Cloud.Sdk.Api; +using GroupDocs.Viewer.Cloud.Sdk.Client; +using GroupDocs.Viewer.Cloud.Sdk.Model; +using GroupDocs.Viewer.Cloud.Sdk.Model.Requests; +using System; +using System.Diagnostics; +using System.IO; + +namespace GroupDocs.Viewer.Cloud.Tutorial +{ + class Program + { + static void Main(string[] args) + { + // Get your client ID and client secret from https://dashboard.groupdocs.cloud/ + string MyClientId = "YOUR_CLIENT_ID"; + string MyClientSecret = "YOUR_CLIENT_SECRET"; + + // Create API instance + var configuration = new Configuration(MyClientId, MyClientSecret); + var apiInstance = new ViewApi(configuration); + + // Define rendering options + var viewOptions = new ViewOptions + { + FileInfo = new FileInfo + { + FilePath = "SampleFiles/sample.docx" + }, + ViewFormat = ViewOptions.ViewFormatEnum.PDF + }; + + try + { + // Call the API to render the document + var response = apiInstance.CreateView(new CreateViewRequest(viewOptions)); + + Console.WriteLine("Document rendered to PDF successfully!"); + + // Print information about the rendered PDF + Console.WriteLine($"PDF file path: {response.File.Path}"); + Console.WriteLine($"Download URL: {response.File.DownloadUrl}"); + + // Download the rendered PDF (optional) + using (var webClient = new System.Net.WebClient()) + { + webClient.Headers.Add("Authorization", "Bearer " + configuration.GetToken()); + webClient.DownloadFile(response.File.DownloadUrl, "rendered_document.pdf"); + Console.WriteLine("PDF downloaded as rendered_document.pdf"); + } + + // Open the PDF in default viewer + Process.Start(new ProcessStartInfo + { + FileName = "rendered_document.pdf", + UseShellExecute = true + }); + } + catch (Exception e) + { + Console.WriteLine("Exception while calling ViewApi: " + e.Message); + } + + Console.WriteLine("Press any key to exit..."); + Console.ReadKey(); + } + } +} +``` + +### Python Example + +```python +# Import modules +import os +import webbrowser +import requests +import groupdocs_viewer_cloud + +# Get your client ID and client secret from https://dashboard.groupdocs.cloud/ +client_id = "YOUR_CLIENT_ID" +client_secret = "YOUR_CLIENT_SECRET" + +# Create API instance +api_instance = groupdocs_viewer_cloud.ViewApi.from_keys(client_id, client_secret) + +# Define rendering options +view_options = groupdocs_viewer_cloud.ViewOptions() +view_options.file_info = groupdocs_viewer_cloud.FileInfo() +view_options.file_info.file_path = "SampleFiles/sample.docx" +view_options.view_format = "PDF" + +try: + # Call the API to render the document + request = groupdocs_viewer_cloud.CreateViewRequest(view_options) + response = api_instance.create_view(request) + + print("Document rendered to PDF successfully!") + + # Print information about the rendered PDF + print(f"PDF file path: {response.file.path}") + print(f"Download URL: {response.file.download_url}") + + # Download the rendered PDF (optional) + pdf_response = requests.get( + response.file.download_url, + headers={"Authorization": f"Bearer {api_instance.configuration.access_token}"} + ) + + if pdf_response.status_code == 200: + with open("rendered_document.pdf", "wb") as file: + file.write(pdf_response.content) + print("PDF downloaded as rendered_document.pdf") + + # Open the PDF in default viewer + pdf_path = os.path.abspath("rendered_document.pdf") + print(f"Opening {pdf_path} in default PDF viewer") + webbrowser.open(f'file://{pdf_path}') + +except groupdocs_viewer_cloud.ApiException as e: + print(f"Exception while calling ViewApi: {e}") +``` + +## Try It Yourself + +Now that you've seen how to render documents to PDF using GroupDocs.Viewer Cloud API, try it with your own documents. Experiment with different file types like Excel spreadsheets, PowerPoint presentations, images, or CAD drawings. + +### Exercise: Customize PDF Output + +Try to modify the examples above to: +1. Render only specific pages of a document to PDF +2. Add security to the PDF output with passwords and permissions +3. Optimize the PDF for reduced file size + +## Advanced PDF Features + +GroupDocs.Viewer Cloud API offers several advanced PDF rendering features: + +### PDF Security + +You can add password protection and set permissions to restrict what users can do with the PDF: + +```csharp +var viewOptions = new ViewOptions +{ + FileInfo = new FileInfo + { + FilePath = "SampleFiles/sample.docx" + }, + ViewFormat = ViewOptions.ViewFormatEnum.PDF, + RenderOptions = new PdfOptions + { + DocumentOpenPassword = "openPassword", + PermissionsPassword = "permissionsPassword", + Permissions = new List { "DenyPrinting", "DenyModification" } + } +}; +``` + +### PDF Optimization + +You can optimize the PDF output for reduced file size by compressing images and other content: + +```csharp +var viewOptions = new ViewOptions +{ + FileInfo = new FileInfo + { + FilePath = "SampleFiles/sample.docx" + }, + ViewFormat = ViewOptions.ViewFormatEnum.PDF, + RenderOptions = new PdfOptions + { + PdfOptimizationOptions = new PdfOptimizationOptions + { + CompressImages = true, + ImageQuality = 80 + } + } +}; +``` + +## Troubleshooting Tips + +- Authentication Issues: Ensure your Client ID and Client Secret are correct and that you're generating a fresh JWT token +- File Not Found: Verify that the file path in your request matches the actual path in cloud storage +- Large Files: When working with very large documents, you might need to increase timeout values in your code +- PDF Features: Not all features are supported for all document types - check the API documentation for details + +## What You've Learned + +In this tutorial, you've learned: +- How to authenticate with the GroupDocs.Viewer Cloud API +- How to upload documents to cloud storage +- How to render documents to PDF format +- How to download and use the rendered PDF +- How to implement PDF rendering in your applications using SDKs +- How to use advanced PDF features like security and optimization + +## Helpful Resources + +- [Product Page](https://products.groupdocs.cloud/viewer/) +- [Documentation](https://docs.groupdocs.cloud/viewer/) +- [Live Demo](https://products.groupdocs.app/viewer/family) +- [API Reference](https://reference.groupdocs.cloud/viewer/) +- [Blog](https://blog.groupdocs.cloud/categories/groupdocs.viewer-cloud-product-family/) +- [Free Support Forum](https://forum.groupdocs.cloud/c/viewer/9) +- [Free Trial](https://dashboard.groupdocs.cloud/#/apps) + +## Feedback and Questions + +Have questions about this tutorial? Need help implementing PDF viewing in your application? We welcome your feedback and questions on our [support forum](https://forum.groupdocs.cloud/c/viewer/9). diff --git a/content/viewer/english/data-structures/_index.md b/content/viewer/english/data-structures/_index.md new file mode 100644 index 0000000..9486195 --- /dev/null +++ b/content/viewer/english/data-structures/_index.md @@ -0,0 +1,65 @@ +--- +title: GroupDocs.Viewer Cloud API Document Data Structures Tutorials +weight: 10 +url: /data-structures/ +description: Learn how to use GroupDocs.Viewer Cloud API data structures with these step-by-step tutorials for developers +--- + +# Document Data Structures Tutorials for GroupDocs.Viewer Cloud API + +Welcome to our comprehensive tutorial series on GroupDocs.Viewer Cloud API Document Data Structures. These hands-on tutorials are designed specifically for developers who want to master document rendering and viewing capabilities in their applications. + +## What You'll Learn + +These step-by-step guides will take you from understanding basic data structures to implementing advanced document viewing features in your applications. By following this learning path, you'll gain practical knowledge that you can immediately apply to your development projects. + +## Learning Path: From Basics to Advanced + +### Foundation Tutorials + +1. [Learn to Use ViewOptions Tutorial](/data-structures/view-options/) - Master the fundamental data structure for specifying how documents should be viewed and rendered. + +2. [RenderOptions Tutorial: Controlling Document Rendering](/data-structures/render-options/) - Learn how to fine-tune the rendering process with detailed configuration options. + +### Format-Specific Rendering Tutorials + +3. [HTML Rendering Tutorial with HtmlOptions](/data-structures/html-options/) - Step-by-step instructions for HTML-based document viewing with responsive layouts. + +4. [Image Rendering Tutorial with ImageOptions](/data-structures/image-options/) - Learn to convert documents to high-quality JPG/PNG images with customizable parameters. + +### Advanced Tutorials + +5. [PDF Optimization Tutorial with PdfOptimizationOptions](/data-structures/pdf-optimization-options/) - Learn techniques to optimize PDF output for size and performance. + +6. [Working with ViewResult Tutorial](/data-structures/view-result/) - Master handling the output results from document rendering operations. + +7. [Document Information Tutorial with InfoResult](/data-structures/info-result/) - Extract and utilize document metadata and structure information. + +8. [Tutorial: How to Delete Views with DeleteViewOptions](/data-structures/delete-view-options/) - Learn the proper way to clean up rendered document views. + +## Prerequisites + +Before starting these tutorials, ensure you have: + +- A [GroupDocs.Viewer Cloud account](https://dashboard.groupdocs.cloud) +- Your API credentials (Client ID and Client Secret) +- Basic knowledge of RESTful APIs +- Familiarity with your preferred programming language (examples provided in multiple languages) + +## Getting Started + +Each tutorial is designed to be completed in 15-30 minutes and includes complete code examples. We recommend following the tutorials in the order listed above for the best learning experience. + +Ready to start? Begin with our [ViewOptions Tutorial](/data-structures/view-options/) to learn the fundamentals of document viewing configuration. + +## Helpful Resources + +- [Product Page](https://products.groupdocs.cloud/viewer/) +- [Documentation](https://docs.groupdocs.cloud/viewer/) +- [Live Demo](https://products.groupdocs.app/viewer/family) +- [API Reference UI](https://reference.groupdocs.cloud/viewer/) +- [Blog](https://blog.groupdocs.cloud/categories/groupdocs.viewer-cloud-product-family/) +- [Free Support](https://forum.groupdocs.cloud/c/viewer/9) +- [Free Trial](https://dashboard.groupdocs.cloud/#/apps) + +Have questions about these tutorials? Feel free to reach out on our [support forum](https://forum.groupdocs.cloud/c/viewer/9) for assistance. diff --git a/content/viewer/english/data-structures/delete-view-options/_index.md b/content/viewer/english/data-structures/delete-view-options/_index.md new file mode 100644 index 0000000..1bec6ac --- /dev/null +++ b/content/viewer/english/data-structures/delete-view-options/_index.md @@ -0,0 +1,360 @@ +--- +title: How to Delete Views with DeleteViewOptions Tutorial +url: /data-structures/delete-view-options/ +weight: 9 +description: Learn how to manage rendered document views in this step-by-step DeleteViewOptions tutorial for GroupDocs.Viewer Cloud API +--- + +# Tutorial: How to Delete Views with DeleteViewOptions + +## Learning Objectives + +In this tutorial, you'll learn: +- Why and when to delete rendered document views +- How to use DeleteViewOptions to clean up storage space +- Best practices for document view management +- Implementation strategies for different scenarios + +## Prerequisites + +Before starting this tutorial: +- Complete the [ViewOptions Tutorial](/data-structures/view-options/) +- Have your GroupDocs.Viewer Cloud API credentials ready +- Understand basic document rendering concepts + +## Introduction to DeleteViewOptions + +The DeleteViewOptions data structure is used to specify which rendered document views should be deleted from storage. When you render documents with GroupDocs.Viewer Cloud, the output files (HTML pages, images, PDF) are stored in your cloud storage. The DeleteViewOptions structure lets you clean up these files when they're no longer needed. + +Proper view management is essential for: +- Keeping your storage space optimized +- Removing outdated rendered content +- Maintaining document security +- Implementing document workflow lifecycles + +## Understanding the DeleteViewOptions Structure + +DeleteViewOptions has a simple structure with one primary component: + +- FileInfo: Contains information about the document whose views should be deleted + +Let's explore how to use this structure with practical examples. + +## Tutorial Steps + +### Step 1: Basic View Deletion + +Let's start with a simple example of deleting views for a document: + +```python +# Tutorial Code Example: Basic view deletion +import os +from groupdocs_viewer_cloud import Configuration, ViewerApi, DeleteViewOptions, FileInfo + +# Configure the API client +configuration = Configuration(client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET") +viewer_api = ViewerApi.from_config(configuration) + +# Set up file info for the document whose views we want to delete +file_info = FileInfo() +file_info.file_path = "documents/sample.docx" + +# Create delete view options +delete_options = DeleteViewOptions() +delete_options.file_info = file_info + +# Delete all rendered views for this document +viewer_api.delete_view(delete_options) + +print(f"Successfully deleted all rendered views for: {file_info.file_path}") +``` + +### Step 2: Understanding What Gets Deleted + +When you call the delete_view method, what exactly gets removed? Let's see with an example: + +```python +# Tutorial Code Example: Understanding what gets deleted +from groupdocs_viewer_cloud import ViewOptions, HtmlOptions, DeleteViewOptions, FileInfo + +# First render a document to HTML +file_info = FileInfo() +file_info.file_path = "documents/document.pdf" + +# Create HTML options +html_options = HtmlOptions() + +# Set up view options +view_options = ViewOptions() +view_options.file_info = file_info +view_options.view_format = "HTML" +view_options.render_options = html_options +view_options.output_path = "output/document_html" + +# Render the document +result = viewer_api.view(view_options) + +print(f"Document rendered to HTML with {len(result.pages)} pages") +print(f"Output path: {view_options.output_path}") +for page in result.pages[:2]: # Show first two pages + print(f" - Page {page.number}: {page.path}") + +# Now delete the rendered views +delete_options = DeleteViewOptions() +delete_options.file_info = file_info + +# Delete all rendered views +viewer_api.delete_view(delete_options) + +print(f"\nDeleted all rendered views at: {view_options.output_path}") +print("This includes all HTML pages and resources that were created during rendering") +``` + +### Step 3: Implementing a Render-Use-Delete Workflow + +For applications with limited storage or security requirements, implementing a complete workflow is ideal: + +```python +# Tutorial Code Example: Render-use-delete workflow +from groupdocs_viewer_cloud import ViewOptions, PdfOptions, DeleteViewOptions, FileInfo + +# Set up file info +file_info = FileInfo() +file_info.file_path = "documents/confidential-report.docx" + +# Step 1: Render document to PDF +pdf_options = PdfOptions() + +view_options = ViewOptions() +view_options.file_info = file_info +view_options.view_format = "PDF" +view_options.render_options = pdf_options +view_options.output_path = "output/temp_pdf" + +# Render the document +result = viewer_api.view(view_options) + +print(f"Document rendered to PDF: {result.file}") + +# Step 2: Process or use the rendered document +# In a real application, you might: +# - Provide the PDF to the user for download +# - Process the PDF further +# - Store it in a different location +print("Processing the PDF file...") +print("For example, allowing user to download it...") + +# Step 3: Delete the rendered view when finished +delete_options = DeleteViewOptions() +delete_options.file_info = file_info + +# Delete all rendered views +viewer_api.delete_view(delete_options) + +print(f"\nDeleted temporary PDF file after processing") +print("This keeps your storage clean and ensures temporary files aren't left behind") +``` + +### Step 4: Integrating Delete Operations in a User Session + +Here's how you might integrate view deletion into a user session lifecycle: + +```python +# Tutorial Code Example: Session-based document viewing +from groupdocs_viewer_cloud import ViewOptions, HtmlOptions, DeleteViewOptions, FileInfo +import time + +# Simulate a user session +print("User session started") +print("User requests to view a document") + +# Set up file info +file_info = FileInfo() +file_info.file_path = "documents/large-report.xlsx" + +# Create HTML options with responsive design +html_options = HtmlOptions() +html_options.is_responsive = True + +# Generate a unique session ID (in real app, this would be a session token) +session_id = f"session_{int(time.time())}" + +# Set up view options with session-specific output path +view_options = ViewOptions() +view_options.file_info = file_info +view_options.view_format = "HTML" +view_options.render_options = html_options +view_options.output_path = f"output/sessions/{session_id}" + +# Render the document +result = viewer_api.view(view_options) + +print(f"Document rendered to HTML with {len(result.pages)} pages") +print(f"Session-specific output path: {view_options.output_path}") + +# Simulate user viewing the document +print("User is viewing the document...") +time.sleep(2) # In a real application, this would be actual user interaction time + +# Simulate session end (user logs out or session expires) +print("User session ended") + +# Clean up session resources +delete_options = DeleteViewOptions() +delete_options.file_info = file_info + +# Delete all rendered views +viewer_api.delete_view(delete_options) + +print(f"\nSession cleanup: Deleted all rendered views for session {session_id}") +print("This prevents storage bloat and protects document confidentiality") +``` + +### Step 5: Scheduled Cleanup Operations + +For long-running applications, implementing scheduled cleanup is a good practice: + +```python +# Tutorial Code Example: Scheduled cleanup operations +from groupdocs_viewer_cloud import DeleteViewOptions, FileInfo +import datetime + +# This would typically run as a scheduled task or cron job +def run_scheduled_cleanup(): + print(f"Starting scheduled cleanup at {datetime.datetime.now()}") + + # In a real application, you would have a database or log of rendered documents + # Here we'll use a simple list for demonstration + documents_to_clean = [ + {"path": "documents/report1.docx", "render_date": "2023-08-15"}, + {"path": "documents/invoice.pdf", "render_date": "2023-08-16"}, + {"path": "documents/presentation.pptx", "render_date": "2023-08-17"} + ] + + # Get current date for age comparison + current_date = datetime.datetime.now().date() + + # Process each document + for doc in documents_to_clean: + file_path = doc["path"] + render_date = datetime.datetime.strptime(doc["render_date"], "%Y-%m-%d").date() + + # Calculate age in days + age_days = (current_date - render_date).days + + # If rendered view is older than 7 days, delete it + if age_days > 7: + file_info = FileInfo() + file_info.file_path = file_path + + delete_options = DeleteViewOptions() + delete_options.file_info = file_info + + # Delete all rendered views + viewer_api.delete_view(delete_options) + + print(f"Deleted rendered views for {file_path} (age: {age_days} days)") + else: + print(f"Keeping rendered views for {file_path} (age: {age_days} days)") + + print(f"Scheduled cleanup completed at {datetime.datetime.now()}") + +# Run the cleanup function +run_scheduled_cleanup() +``` + +### Step 6: Implementing Version-Based Cleanup + +When documents are updated, you might want to clean up older rendered versions: + +```python +# Tutorial Code Example: Version-based cleanup +from groupdocs_viewer_cloud import ViewOptions, HtmlOptions, DeleteViewOptions, FileInfo + +# Scenario: A document has been updated, and we need to re-render and replace old views + +# Document information +document_path = "documents/company-policy.docx" +document_version = "v2" # Current version + +# Step 1: Delete previous rendered views +delete_options = DeleteViewOptions() +delete_options.file_info = FileInfo(file_path=document_path) + +# Delete all rendered views of previous version +viewer_api.delete_view(delete_options) + +print(f"Deleted previously rendered views for {document_path}") + +# Step 2: Render new version +file_info = FileInfo() +file_info.file_path = document_path + +# Create HTML options +html_options = HtmlOptions() +html_options.is_responsive = True + +# Set up view options with version in the output path +view_options = ViewOptions() +view_options.file_info = file_info +view_options.view_format = "HTML" +view_options.render_options = html_options +view_options.output_path = f"output/{document_version}/{document_path}" + +# Render the document +result = viewer_api.view(view_options) + +print(f"Rendered new version ({document_version}) to HTML with {len(result.pages)} pages") +print(f"New version output path: {view_options.output_path}") + +print("\nThis version management approach ensures users always see the latest document version") +``` + +## Try It Yourself + +Now that you've learned how to use DeleteViewOptions, try these exercises: + +1. Implement a document viewer that automatically cleans up rendered files after a specified time period +2. Create a batch cleanup operation that removes all rendered views for documents in a specific folder +3. Build a version-based document management system that maintains only the latest rendered views + +## Troubleshooting Tips + +- Nothing seems to be deleted: Verify that the file path in FileInfo matches exactly what was used when rendering +- Error during deletion: Check if you have proper permissions to delete files in the storage +- Unable to find rendered views: Ensure you're looking in the correct output path + +## Best Practices + +1. Clean up promptly: Delete rendered views as soon as they're no longer needed +2. Use unique output paths: Organize rendered views by user, session, or version to make cleanup easier +3. Implement scheduled cleanup: Set up regular maintenance to remove old rendered views +4. Log cleanup operations: Keep records of what was deleted and when for troubleshooting +5. Check deletion success: Verify that cleanup operations completed successfully + +## What You've Learned + +In this tutorial, you've mastered: +- How to use DeleteViewOptions to clean up rendered document views +- Implementing complete document viewing workflows with proper cleanup +- Session-based view management strategies +- Scheduled and version-based cleanup approaches +- Best practices for maintaining optimal storage usage + +## Next Steps + +Congratulations! You've completed all the tutorials in our Document Data Structures series. To continue your learning journey with GroupDocs.Viewer Cloud API, consider exploring these advanced topics: + +- [Viewer API Working with Storage](https://docs.groupdocs.cloud/viewer/working-with-storage/) +- [Viewer API Working with Folders](https://docs.groupdocs.cloud/viewer/working-with-folders/) +- [Viewer API Working with Files](https://docs.groupdocs.cloud/viewer/working-with-files/) + +## Helpful Resources + +- [Product Page](https://products.groupdocs.cloud/viewer/) +- [Documentation](https://docs.groupdocs.cloud/viewer/) +- [API Reference UI](https://reference.groupdocs.cloud/viewer/) +- [Free Support](https://forum.groupdocs.cloud/c/viewer/9) +- [Free Trial](https://dashboard.groupdocs.cloud/#/apps) + +Have questions about document view management? Post them on our [support forum](https://forum.groupdocs.cloud/c/viewer/9). diff --git a/content/viewer/english/data-structures/html-options/_index.md b/content/viewer/english/data-structures/html-options/_index.md new file mode 100644 index 0000000..cf05dde --- /dev/null +++ b/content/viewer/english/data-structures/html-options/_index.md @@ -0,0 +1,340 @@ +--- +title: HTML Rendering with HtmlOptions Tutorial +url: /data-structures/html-options/ +weight: 3 +description: Learn how to create responsive HTML document views with this step-by-step HtmlOptions tutorial for GroupDocs.Viewer Cloud API +--- + +# Tutorial: HTML Rendering with HtmlOptions + +## Learning Objectives + +In this tutorial, you'll learn: +- How to render documents to HTML format using HtmlOptions +- Techniques for creating responsive document views +- Methods for managing external resource handling +- How to customize resource paths for better integration + +## Prerequisites + +Before starting this tutorial: +- Complete the [ViewOptions Tutorial](/data-structures/view-options/) +- Have your GroupDocs.Viewer Cloud API credentials ready +- Prepare sample documents of various formats (DOCX, PDF, PPTX) + +## Introduction to HtmlOptions + +HtmlOptions is a specialized data structure that inherits from RenderOptions and provides HTML-specific rendering configurations. When you need to render documents to HTML format, this structure gives you fine control over how the HTML output is generated and how resources are handled. + +HTML rendering is ideal for web applications, online document viewers, and situations where interactive document viewing is required. + +## Understanding the HtmlOptions Structure + +HtmlOptions adds these key HTML-specific properties to the base RenderOptions: + +- ExternalResources: Controls whether to embed or externalize resources +- ResourcePath: Defines the path template for externalized resources +- IsResponsive: Enables responsive output for better display on various devices + +Let's explore these options with practical examples. + +## Tutorial Steps + +### Step 1: Basic HTML Rendering + +Let's start with a simple HTML rendering setup: + +```python +# Tutorial Code Example: Basic HTML rendering +import os +from groupdocs_viewer_cloud import Configuration, ViewerApi, ViewOptions, HtmlOptions, FileInfo + +# Configure the API client +configuration = Configuration(client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET") +viewer_api = ViewerApi.from_config(configuration) + +# Set up file info +file_info = FileInfo() +file_info.file_path = "documents/sample-presentation.pptx" + +# Create basic HTML options +html_options = HtmlOptions() +# Use default settings (embedded resources, non-responsive) + +# Set up view options +view_options = ViewOptions() +view_options.file_info = file_info +view_options.view_format = "HTML" +view_options.render_options = html_options +view_options.output_path = "output/presentation_html" + +# Render the document +result = viewer_api.view(view_options) + +print(f"Document rendered to HTML: {len(result.pages)} pages created") +for page in result.pages: + print(f"Page {page.number} path: {page.path}") + # With default settings, resources are embedded in HTML + print(f"Resources count: {len(page.resources)}") # Should be 0 with embedded resources +``` + +### Step 2: Creating Responsive HTML Output + +For better viewing on mobile devices and various screen sizes, you can enable responsive rendering: + +```python +# Tutorial Code Example: Responsive HTML rendering +from groupdocs_viewer_cloud import ViewOptions, HtmlOptions, FileInfo + +# Set up file info +file_info = FileInfo() +file_info.file_path = "documents/annual-report.pdf" + +# Create responsive HTML options +html_options = HtmlOptions() +html_options.is_responsive = True # Enable responsive layout + +# Set up view options +view_options = ViewOptions() +view_options.file_info = file_info +view_options.view_format = "HTML" +view_options.render_options = html_options +view_options.output_path = "output/responsive_html" + +# Render the document +result = viewer_api.view(view_options) + +print(f"Document rendered to responsive HTML: {len(result.pages)} pages created") +print("The HTML output will adapt to different screen sizes automatically") +``` + +### Step 3: Working with External Resources + +For better performance and more flexibility, you can separate resources (images, fonts, stylesheets) from HTML: + +```python +# Tutorial Code Example: HTML rendering with external resources +from groupdocs_viewer_cloud import ViewOptions, HtmlOptions, FileInfo + +# Set up file info +file_info = FileInfo() +file_info.file_path = "documents/whitepaper.docx" + +# Create HTML options with external resources +html_options = HtmlOptions() +html_options.external_resources = True # Extract resources as separate files +html_options.resource_path = "viewer/resources/{resource-name}" # Resource path template + +# Set up view options +view_options = ViewOptions() +view_options.file_info = file_info +view_options.view_format = "HTML" +view_options.render_options = html_options +view_options.output_path = "output/whitepaper_html" + +# Render the document +result = viewer_api.view(view_options) + +print(f"Document rendered with external resources: {len(result.pages)} pages") +for page in result.pages: + print(f"Page {page.number} has {len(page.resources)} external resources:") + for resource in page.resources[:3]: # Show first 3 resources as example + print(f" - {resource.name} ({resource.file_type})") +``` + +### Step 4: Customizing Resource Path Templates + +You can customize how resource paths are structured using template placeholders: + +```python +# Tutorial Code Example: Custom resource path templates +from groupdocs_viewer_cloud import ViewOptions, HtmlOptions, FileInfo + +# Set up file info +file_info = FileInfo() +file_info.file_path = "documents/financial-charts.pptx" + +# Create HTML options with custom resource path +html_options = HtmlOptions() +html_options.external_resources = True +# Define a path template with page number and resource name placeholders +html_options.resource_path = "content/viewer/{page-number}/resources/{resource-name}" + +# Set up view options +view_options = ViewOptions() +view_options.file_info = file_info +view_options.view_format = "HTML" +view_options.render_options = html_options +view_options.output_path = "output/financial_slides" + +# Render the document +result = viewer_api.view(view_options) + +print(f"Document rendered with custom resource paths: {len(result.pages)} pages") +for page in result.pages: + if len(page.resources) > 0: + print(f"Resource example from page {page.number}: {page.resources[0].path}") + # Path will follow the template pattern: content/viewer/1/resources/image1.png +``` + +### Step 5: Combining Responsive Design with External Resources + +For optimal web viewing experience, combine responsive design with external resources: + +```python +# Tutorial Code Example: Responsive design with external resources +from groupdocs_viewer_cloud import ViewOptions, HtmlOptions, FileInfo + +# Set up file info +file_info = FileInfo() +file_info.file_path = "documents/product-catalog.pdf" + +# Create optimized HTML options +html_options = HtmlOptions() +html_options.is_responsive = True # Responsive layout +html_options.external_resources = True # External resources for better caching +html_options.resource_path = "assets/{resource-name}" # Simple resource path + +# Set up view options +view_options = ViewOptions() +view_options.file_info = file_info +view_options.view_format = "HTML" +view_options.render_options = html_options +view_options.output_path = "output/product_catalog" + +# Render the document +result = viewer_api.view(view_options) + +print(f"Created optimized HTML output with responsive design and external resources") +print(f"Total pages: {len(result.pages)}") +print(f"Total resources: {sum(len(page.resources) for page in result.pages)}") +``` + +### Step 6: Practical Integration Example + +Here's how to integrate HTML output with page navigation in a web application: + +```python +# Tutorial Code Example: Integration with web application +from groupdocs_viewer_cloud import ViewOptions, HtmlOptions, FileInfo + +# Set up file info +file_info = FileInfo() +file_info.file_path = "documents/user-manual.pdf" + +# Create HTML options for web integration +html_options = HtmlOptions() +html_options.external_resources = True +html_options.is_responsive = True +html_options.resource_path = "/api/document-viewer/resources/{resource-name}" + +# Set up view options +view_options = ViewOptions() +view_options.file_info = file_info +view_options.view_format = "HTML" +view_options.render_options = html_options +view_options.output_path = "output/user_manual" + +# Render the document +result = viewer_api.view(view_options) + +# Generate example HTML to demonstrate integration +print("Example HTML for web integration:") +print("html") +print("") +print("") +print("") +print(" Document Viewer") +print(" ") +print("") +print("") +print("
") +print("
") +print(" ") +print(" 1 / " + str(len(result.pages)) + "") +print(" ") +print("
") +print("
") +print(" ") +print("
") +print("
") +print("") +print(" ") +print("") +print("") +print("") +``` + +## Try It Yourself + +Now that you've learned how to use HtmlOptions, try these exercises: + +1. Render a PPTX file with responsive layout and external resources +2. Create a simple web viewer that displays a PDF document with navigation controls +3. Experiment with different resource path templates and observe the results + +## Troubleshooting Tips + +- Missing resources: If resources are missing, make sure `external_resources` is set to `true` +- Resource path issues: Check that the `resource_path` template contains the required placeholders (`{resource-name}`) +- Responsive layout not working: Verify that `is_responsive` is set to `true` and test on different devices + +## What You've Learned + +In this tutorial, you've mastered: +- How to configure basic HTML rendering +- Creating responsive HTML output for better viewing across devices +- Working with external resources for improved performance +- Customizing resource paths for seamless integration with web applications +- Combining various HtmlOptions settings for optimal document viewing + +## Next Steps + +Ready to explore other rendering formats? Continue your learning with our [Image Rendering Tutorial](/data-structures/image-options/) to discover how to convert documents to high-quality images. + +## Helpful Resources + +- [Product Page](https://products.groupdocs.cloud/viewer/) +- [Documentation](https://docs.groupdocs.cloud/viewer/) +- [API Reference UI](https://reference.groupdocs.cloud/viewer/) +- [Free Support](https://forum.groupdocs.cloud/c/viewer/9) +- [Free Trial](https://dashboard.groupdocs.cloud/#/apps) + +Have questions about HTML rendering? Post them on our [support forum](https://forum.groupdocs.cloud/c/viewer/9). diff --git a/content/viewer/english/data-structures/image-options/_index.md b/content/viewer/english/data-structures/image-options/_index.md new file mode 100644 index 0000000..2893d39 --- /dev/null +++ b/content/viewer/english/data-structures/image-options/_index.md @@ -0,0 +1,354 @@ +--- +title: Image Rendering with ImageOptions Tutorial +url: /data-structures/image-options/ +weight: 4 +description: Learn how to convert documents to high-quality images in this step-by-step ImageOptions tutorial for GroupDocs.Viewer Cloud API +--- + +# Tutorial: Image Rendering with ImageOptions + +## Learning Objectives + +In this tutorial, you'll learn: +- How to render documents to JPG and PNG formats using ImageOptions +- Techniques for controlling image dimensions and quality +- Methods for extracting text to enable search capabilities +- Best practices for image-based document viewing + +## Prerequisites + +Before starting this tutorial: +- Complete the [ViewOptions Tutorial](/data-structures/view-options) +- Have your GroupDocs.Viewer Cloud API credentials ready +- Prepare sample documents of various formats (PDF, DOCX, presentations) + +## Introduction to ImageOptions + +ImageOptions is a specialized data structure that inherits from RenderOptions and provides image-specific rendering configurations. When you need to convert documents to image formats (JPG or PNG), this structure gives you precise control over image dimensions, quality, and text extraction. + +Image rendering is ideal for universal compatibility, protecting document content from editing, or when you need pixel-perfect representation across all devices. + +## Understanding the ImageOptions Structure + +ImageOptions adds these key image-specific properties to the base RenderOptions: + +- Width/Height: Control output image dimensions +- JpegQuality: Adjust compression level for JPG output +- ExtractText: Enable text extraction for searchability + +Let's explore these options with practical examples. + +## Tutorial Steps + +### Step 1: Basic Image Rendering + +Let's start with a simple image rendering setup: + +```python +# Tutorial Code Example: Basic image rendering +import os +from groupdocs_viewer_cloud import Configuration, ViewerApi, ViewOptions, ImageOptions, FileInfo + +# Configure the API client +configuration = Configuration(client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET") +viewer_api = ViewerApi.from_config(configuration) + +# Set up file info +file_info = FileInfo() +file_info.file_path = "documents/contract.pdf" + +# Create basic image options +image_options = ImageOptions() +# Use default settings + +# Set up view options +view_options = ViewOptions() +view_options.file_info = file_info +view_options.view_format = "JPG" # Can also use "PNG" +view_options.render_options = image_options +view_options.output_path = "output/contract_images" + +# Render the document +result = viewer_api.view(view_options) + +print(f"Document rendered to JPG images: {len(result.pages)} pages created") +for page in result.pages: + print(f"Page {page.number} path: {page.path}") +``` + +### Step 2: Controlling Image Dimensions + +You can specify exact dimensions for your output images: + +```python +# Tutorial Code Example: Setting image dimensions +from groupdocs_viewer_cloud import ViewOptions, ImageOptions, FileInfo + +# Set up file info +file_info = FileInfo() +file_info.file_path = "documents/presentation.pptx" + +# Create image options with custom dimensions +image_options = ImageOptions() +image_options.width = 1024 # Width in pixels +image_options.height = 768 # Height in pixels + +# Set up view options +view_options = ViewOptions() +view_options.file_info = file_info +view_options.view_format = "PNG" # PNG for better quality +view_options.render_options = image_options +view_options.output_path = "output/presentation_images" + +# Render the document +result = viewer_api.view(view_options) + +print(f"Document rendered to 1024x768 PNG images: {len(result.pages)} pages") +``` + +### Step 3: Maintaining Aspect Ratio + +To maintain the aspect ratio while resizing, you can set only one dimension: + +```python +# Tutorial Code Example: Maintaining aspect ratio +from groupdocs_viewer_cloud import ViewOptions, ImageOptions, FileInfo + +# Set up file info +file_info = FileInfo() +file_info.file_path = "documents/magazine.pdf" + +# Create image options preserving aspect ratio +image_options = ImageOptions() +image_options.width = 800 # Set only width +image_options.height = 0 # Height will be calculated automatically + +# Set up view options +view_options = ViewOptions() +view_options.file_info = file_info +view_options.view_format = "JPG" +view_options.render_options = image_options +view_options.output_path = "output/magazine_images" + +# Render the document +result = viewer_api.view(view_options) + +print(f"Document rendered with preserved aspect ratio") +print(f"All images have width of 800px with proportional height") +``` + +### Step 4: Adjusting JPEG Quality + +For JPG output, you can control the compression level to balance file size and quality: + +```python +# Tutorial Code Example: Adjusting JPEG quality +from groupdocs_viewer_cloud import ViewOptions, ImageOptions, FileInfo + +# Set up file info +file_info = FileInfo() +file_info.file_path = "documents/large-document.pdf" + +# Create image options with quality settings +image_options = ImageOptions() +image_options.jpeg_quality = 75 # 75% quality (range: 1-100) + # Lower values = smaller files but lower quality + +# Set up view options +view_options = ViewOptions() +view_options.file_info = file_info +view_options.view_format = "JPG" +view_options.render_options = image_options +view_options.output_path = "output/optimized_images" + +# Render the document +result = viewer_api.view(view_options) + +print(f"Document rendered with 75% JPEG quality for optimal file size") +``` + +### Step 5: Extracting Text for Searchability + +One limitation of image-based rendering is that text isn't normally searchable. You can overcome this: + +```python +# Tutorial Code Example: Extracting text for searchability +from groupdocs_viewer_cloud import ViewOptions, ImageOptions, FileInfo + +# Set up file info +file_info = FileInfo() +file_info.file_path = "documents/report.pdf" + +# Create image options with text extraction +image_options = ImageOptions() +image_options.extract_text = True # Enable text extraction +image_options.width = 1200 # Set width for better readability +image_options.jpeg_quality = 90 # Higher quality for text clarity + +# Set up view options +view_options = ViewOptions() +view_options.file_info = file_info +view_options.view_format = "JPG" +view_options.render_options = image_options +view_options.output_path = "output/searchable_report" + +# Render the document +result = viewer_api.view(view_options) + +print(f"Document rendered with extracted text layer for searchability") +print(f"You can now implement text search on the image-based viewer") +``` + +### Step 6: Creating a High-Resolution Output + +For printing or detailed viewing, you might need high-resolution images: + +```python +# Tutorial Code Example: High-resolution output +from groupdocs_viewer_cloud import ViewOptions, ImageOptions, FileInfo + +# Set up file info +file_info = FileInfo() +file_info.file_path = "documents/detailed-diagram.pdf" + +# Create high-resolution image options +image_options = ImageOptions() +image_options.width = 2400 # High resolution width +image_options.height = 0 # Maintain aspect ratio +image_options.jpeg_quality = 100 # Maximum quality + +# Set up view options +view_options = ViewOptions() +view_options.file_info = file_info +view_options.view_format = "PNG" # PNG for lossless quality +view_options.render_options = image_options +view_options.output_path = "output/hires_diagram" + +# Render the document +result = viewer_api.view(view_options) + +print(f"Document rendered in high resolution for detailed viewing or printing") +``` + +### Step 7: Practical Integration Example + +Here's how to integrate image-based rendering with a simple viewer interface: + +```python +# Tutorial Code Example: Image viewer integration +from groupdocs_viewer_cloud import ViewOptions, ImageOptions, FileInfo + +# Set up file info +file_info = FileInfo() +file_info.file_path = "documents/whitepaper.pdf" + +# Create optimized image options +image_options = ImageOptions() +image_options.width = 1000 # Standard width +image_options.jpeg_quality = 85 # Good balance of quality and file size +image_options.extract_text = True # Enable text search + +# Set up view options +view_options = ViewOptions() +view_options.file_info = file_info +view_options.view_format = "JPG" +view_options.render_options = image_options +view_options.output_path = "output/whitepaper_images" + +# Render the document +result = viewer_api.view(view_options) + +# Generate example HTML to demonstrate integration +print("Example HTML for image viewer integration:") +print("html") +print("") +print("") +print("") +print(" Document Image Viewer") +print(" ") +print("") +print("") +print("
") +print("
") +print(" ") +print(" 1 / " + str(len(result.pages)) + "") +print(" ") +print("
") +print("
") +print(" \"Document") +print("
") +print("
") +print("") +print(" ") +print("") +print("") +print("") +``` + +## Try It Yourself + +Now that you've learned how to use ImageOptions, try these exercises: + +1. Render a large PDF document to optimized JPG images (balancing quality and file size) +2. Create a simple image viewer that loads document pages on demand +3. Experiment with different width/height combinations and observe how aspect ratio is maintained + +## Troubleshooting Tips + +- Images too large: Reduce width/height or lower JPEG quality to decrease file size +- Text not searchable: Make sure `extract_text` is set to `true` +- Poor quality text: Increase JPEG quality or switch to PNG format for text-heavy documents +- Slow loading: Consider implementing lazy loading in your viewer to only load visible pages + +## What You've Learned + +In this tutorial, you've mastered: +- How to configure basic image rendering +- Controlling image dimensions while maintaining aspect ratio +- Optimizing JPEG quality for the right balance of size and clarity +- Enabling text extraction for searchable image-based viewing +- Building a simple image viewer integration + +## Helpful Resources + +- [Product Page](https://products.groupdocs.cloud/viewer/) +- [Documentation](https://docs.groupdocs.cloud/viewer/) +- [API Reference UI](https://reference.groupdocs.cloud/viewer/) +- [Free Support](https://forum.groupdocs.cloud/c/viewer/9) +- [Free Trial](https://dashboard.groupdocs.cloud/#/apps) + +Have questions about image rendering? Post them on our [support forum](https://forum.groupdocs.cloud/c/viewer/9). diff --git a/content/viewer/english/data-structures/info-result/_index.md b/content/viewer/english/data-structures/info-result/_index.md new file mode 100644 index 0000000..e84c605 --- /dev/null +++ b/content/viewer/english/data-structures/info-result/_index.md @@ -0,0 +1,591 @@ +--- +title: Document Information with InfoResult Tutorial +url: /data-structures/info-result/ +weight: 8 +description: Learn how to extract and analyze document information in this step-by-step InfoResult tutorial for GroupDocs.Viewer Cloud API +--- + +# Tutorial: Document Information with InfoResult + +## Learning Objectives + +In this tutorial, you'll learn: +- How to use the Document Info API to extract document metadata +- Techniques for analyzing document structure and content +- Methods for accessing page dimensions and text content +- How to work with format-specific information like CAD layouts and PDF permissions + +## Prerequisites + +Before starting this tutorial: +- Create a [GroupDocs Cloud account](https://dashboard.groupdocs.cloud) and get your Client ID and Client Secret +- Have basic knowledge of RESTful API concepts +- Prepare sample documents of various formats (PDF, DOCX, CAD, etc.) + +## Introduction to InfoResult + +The InfoResult data structure is what you receive when calling the Document Info API. It provides comprehensive information about a document, including its format, pages, text content, and format-specific details. This information is valuable for document analysis, pre-rendering decisions, and building smarter document viewing applications. + +Think of InfoResult as a document analyzer that lets you understand a document's content and structure before deciding how to process or display it. + +## Understanding the InfoResult Structure + +InfoResult contains several key components: + +- FormatExtension/Format: Document format information +- Pages: List of document pages with dimensions and content +- Attachments: List of document attachments (if any) +- Format-specific information: Special data for CAD files, PDF documents, etc. + +Let's explore these components with practical examples. + +## Tutorial Steps + +### Step 1: Getting Basic Document Information + +Let's start by retrieving basic document information: + +```python +# Tutorial Code Example: Getting basic document information +import os +from groupdocs_viewer_cloud import Configuration, ViewerApi, InfoOptions, FileInfo + +# Configure the API client +configuration = Configuration(client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET") +viewer_api = ViewerApi.from_config(configuration) + +# Set up file info +file_info = FileInfo() +file_info.file_path = "documents/sample.pdf" + +# Create info options +info_options = InfoOptions() +info_options.file_info = file_info + +# Get document information +info_result = viewer_api.get_info(info_options) + +# Display basic document information +print(f"Document format: {info_result.format}") +print(f"File extension: {info_result.format_extension}") +print(f"Total pages: {len(info_result.pages)}") + +# Display page dimensions for the first page +if info_result.pages: + first_page = info_result.pages[0] + print(f"\nFirst page information:") + print(f" - Page number: {first_page.number}") + print(f" - Width: {first_page.width} pixels") + print(f" - Height: {first_page.height} pixels") + print(f" - Visible: {first_page.visible}") +``` + +### Step 2: Extracting Text Content from Pages + +InfoResult can include text content from document pages when requested: + +```python +# Tutorial Code Example: Extracting text content +from groupdocs_viewer_cloud import InfoOptions, FileInfo + +# Set up file info +file_info = FileInfo() +file_info.file_path = "documents/text-document.docx" + +# Create info options with text extraction +info_options = InfoOptions() +info_options.file_info = file_info +info_options.extract_text = True # Request text extraction + +# Get document information with text content +info_result = viewer_api.get_info(info_options) + +# Display text content statistics +print(f"Document has {len(info_result.pages)} pages with text content") + +# Analyze text content from the first page +if info_result.pages and hasattr(info_result.pages[0], 'lines') and info_result.pages[0].lines: + first_page = info_result.pages[0] + lines_count = len(first_page.lines) + print(f"\nText content from first page:") + print(f" - Total lines: {lines_count}") + + # Show first few lines as example + for i, line in enumerate(first_page.lines[:3]): + print(f" - Line {i+1}: {line.value}") + if hasattr(line, 'words') and line.words: + word_count = len(line.words) + print(f" Contains {word_count} words") + + # Count total words on the page + total_words = sum(len(line.words) if hasattr(line, 'words') else 0 for line in first_page.lines) + print(f"\nTotal words on first page: {total_words}") +else: + print("\nNo text content extracted or available") +``` + +### Step 3: Working with Document Attachments + +Some documents may contain attachments that you can identify with InfoResult: + +```python +# Tutorial Code Example: Analyzing document attachments +from groupdocs_viewer_cloud import InfoOptions, FileInfo + +# Set up file info +file_info = FileInfo() +file_info.file_path = "documents/with-attachments.msg" # Email with attachments + +# Create info options +info_options = InfoOptions() +info_options.file_info = file_info + +# Get document information +info_result = viewer_api.get_info(info_options) + +# Check for attachments +if info_result.attachments and len(info_result.attachments) > 0: + print(f"Document contains {len(info_result.attachments)} attachments:") + for i, attachment in enumerate(info_result.attachments): + print(f" {i+1}. {attachment.name}") + + # Generate example code for handling attachments + print("\nExample code for handling attachments:") + print("python") + print("# Process each attachment") + print("for attachment in info_result.attachments:") + print(" # Get the attachment name") + print(" attachment_name = attachment.name") + print(" print(f'Processing attachment: {attachment_name}')") + print(" ") + print(" # Create file info for the attachment") + print(" attachment_file_info = FileInfo()") + print(" attachment_file_info.file_path = f'documents/attachments/{attachment_name}'") + print(" ") + print(" # Now you can process the attachment separately") + print(" # For example, render it to HTML") + print(" attachment_view_options = ViewOptions()") + print(" attachment_view_options.file_info = attachment_file_info") + print(" attachment_view_options.view_format = 'HTML'") + print(" attachment_result = viewer_api.view(attachment_view_options)") + print("") +else: + print("Document does not contain attachments") +``` + +### Step 4: Analyzing PDF-Specific Information + +For PDF documents, InfoResult provides special information about security permissions: + +```python +# Tutorial Code Example: Analyzing PDF-specific information +from groupdocs_viewer_cloud import InfoOptions, FileInfo + +# Set up file info +file_info = FileInfo() +file_info.file_path = "documents/secured.pdf" + +# Create info options +info_options = InfoOptions() +info_options.file_info = file_info + +# Get document information +info_result = viewer_api.get_info(info_options) + +# Check for PDF-specific information +if hasattr(info_result, 'pdf_view_info') and info_result.pdf_view_info: + print(f"PDF document information:") + print(f" - Printing allowed: {info_result.pdf_view_info.printing_allowed}") + + # Make a decision based on printing permission + if info_result.pdf_view_info.printing_allowed: + print(" This document can be printed") + else: + print(" This document has printing restrictions") + + # Print Security Considerations + print("\nSecurity considerations for this PDF:") + if not info_result.pdf_view_info.printing_allowed: + print(" - Disable print button in your viewer application") + print(" - Add a watermark indicating printing is not allowed") + +else: + print("No PDF-specific information available or not a PDF document") +``` + +### Step 5: Working with CAD Drawings Information + +For CAD drawings, InfoResult provides details about layouts and layers: + +```python +# Tutorial Code Example: Analyzing CAD drawing information +from groupdocs_viewer_cloud import InfoOptions, FileInfo + +# Set up file info +file_info = FileInfo() +file_info.file_path = "documents/drawing.dwg" + +# Create info options +info_options = InfoOptions() +info_options.file_info = file_info + +# Get document information +info_result = viewer_api.get_info(info_options) + +# Check for CAD-specific information +if hasattr(info_result, 'cad_view_info') and info_result.cad_view_info: + print(f"CAD drawing information:") + + # Display layouts + if hasattr(info_result.cad_view_info, 'layouts') and info_result.cad_view_info.layouts: + print(f" - Available layouts ({len(info_result.cad_view_info.layouts)}):") + for layout in info_result.cad_view_info.layouts: + print(f" * {layout.name} - {layout.width}x{layout.height}") + + # Display layers + if hasattr(info_result.cad_view_info, 'layers') and info_result.cad_view_info.layers: + print(f"\n - Available layers ({len(info_result.cad_view_info.layers)}):") + for layer in info_result.cad_view_info.layers: + visibility = "Visible" if layer.visible else "Hidden" + print(f" * {layer.name} - {visibility}") + + # Generate example code for rendering specific layout and layers + print("\nExample code for rendering specific layout and layers:") + print("python") + print("from groupdocs_viewer_cloud import ViewOptions, HtmlOptions, CadOptions, FileInfo") + print("") + print("# Set up file info") + print("file_info = FileInfo()") + print("file_info.file_path = 'documents/drawing.dwg'") + print("") + print("# Create CAD options") + print("cad_options = CadOptions()") + if info_result.cad_view_info.layouts and len(info_result.cad_view_info.layouts) > 0: + print(f"cad_options.layout_name = '{info_result.cad_view_info.layouts[0].name}' # Render specific layout") + if info_result.cad_view_info.layers and len(info_result.cad_view_info.layers) > 0: + visible_layers = [layer.name for layer in info_result.cad_view_info.layers if layer.visible] + if visible_layers: + layers_str = "', '".join(visible_layers[:3]) # Take up to 3 layers for example + print(f"cad_options.layers = ['{layers_str}'] # Render specific layers") + print("") + print("# Set up rendering options") + print("html_options = HtmlOptions()") + print("html_options.cad_options = cad_options") + print("") + print("# Set up view options") + print("view_options = ViewOptions()") + print("view_options.file_info = file_info") + print("view_options.view_format = 'HTML'") + print("view_options.render_options = html_options") + print("") + print("# Render the CAD drawing") + print("result = viewer_api.view(view_options)") + print("") +else: + print("No CAD-specific information available or not a CAD drawing") +``` + +### Step 6: Working with Archive Information + +For archive files, InfoResult provides details about the folder structure: + +```python +# Tutorial Code Example: Analyzing archive information +from groupdocs_viewer_cloud import InfoOptions, FileInfo + +# Set up file info +file_info = FileInfo() +file_info.file_path = "documents/archive.zip" + +# Create info options +info_options = InfoOptions() +info_options.file_info = file_info + +# Get document information +info_result = viewer_api.get_info(info_options) + +# Check for archive-specific information +if hasattr(info_result, 'archive_view_info') and info_result.archive_view_info: + print(f"Archive information:") + + # Display folders + if hasattr(info_result.archive_view_info, 'folders') and info_result.archive_view_info.folders: + print(f" - Folders in archive ({len(info_result.archive_view_info.folders)}):") + for folder in info_result.archive_view_info.folders: + print(f" * {folder}") + + # Generate example code for rendering a specific folder + print("\nExample code for rendering a specific folder from the archive:") + print("python") + print("from groupdocs_viewer_cloud import ViewOptions, HtmlOptions, ArchiveOptions, FileInfo") + print("") + print("# Set up file info") + print("file_info = FileInfo()") + print("file_info.file_path = 'documents/archive.zip'") + print("") + print("# Create archive options") + print("html_options = HtmlOptions()") + print("html_options.archive_options = ArchiveOptions()") + if info_result.archive_view_info.folders and len(info_result.archive_view_info.folders) > 0: + print(f"html_options.archive_options.folder = '{info_result.archive_view_info.folders[0]}' # Render specific folder") + print("html_options.archive_options.items_per_page = 15 # Items per page when rendering") + print("") + print("# Set up view options") + print("view_options = ViewOptions()") + print("view_options.file_info = file_info") + print("view_options.view_format = 'HTML'") + print("view_options.render_options = html_options") + print("") + print("# Render the archive contents") + print("result = viewer_api.view(view_options)") + print("") +else: + print("No archive-specific information available or not an archive file") +``` + +### Step 7: Building a Pre-Render Analysis Tool + +Now let's combine our knowledge to build a comprehensive document analysis tool: + +```python +# Tutorial Code Example: Comprehensive document analysis tool +from groupdocs_viewer_cloud import InfoOptions, FileInfo +import json + +# Set up file info +file_info = FileInfo() +file_info.file_path = "documents/unknown-document.pdf" # This could be any format + +# Create info options with text extraction +info_options = InfoOptions() +info_options.file_info = file_info +info_options.extract_text = True # Get text content + +# Get document information +info_result = viewer_api.get_info(info_options) + +# Create comprehensive analysis report +print("Document Analysis Report") +print("======================\n") + +# Basic document information +print(f"Document Type: {info_result.format}") +print(f"Extension: {info_result.format_extension}") +print(f"Total Pages: {len(info_result.pages)}") + +# Page dimensions analysis +if info_result.pages: + # Collect page dimensions + widths = [page.width for page in info_result.pages if hasattr(page, 'width')] + heights = [page.height for page in info_result.pages if hasattr(page, 'height')] + + if widths and heights: + # Analyze page sizes + min_width = min(widths) + max_width = max(widths) + min_height = min(heights) + max_height = max(heights) + avg_width = sum(widths) / len(widths) + avg_height = sum(heights) / len(heights) + + # Check if all pages have same dimensions + uniform_pages = min_width == max_width and min_height == max_height + + print("\nPage Dimensions Analysis:") + print(f" - Page size is {'uniform' if uniform_pages else 'variable'}") + if uniform_pages: + print(f" - All pages are {widths[0]}x{heights[0]} pixels") + else: + print(f" - Width range: {min_width}-{max_width} pixels (avg: {avg_width:.1f})") + print(f" - Height range: {min_height}-{max_height} pixels (avg: {avg_height:.1f})") + + # Determine optimal rendering settings based on page sizes + print("\nRecommended Rendering Settings:") + if max_width > 1000 or max_height > 1400: + print(" - Use high-resolution rendering for detailed content") + + # Page orientation analysis + portrait_pages = sum(1 for w, h in zip(widths, heights) if h > w) + landscape_pages = sum(1 for w, h in zip(widths, heights) if w > h) + square_pages = sum(1 for w, h in zip(widths, heights) if w == h) + + print("\nPage Orientation Analysis:") + print(f" - Portrait pages: {portrait_pages}") + print(f" - Landscape pages: {landscape_pages}") + print(f" - Square pages: {square_pages}") + + if landscape_pages > 0: + print(" - Note: Document contains landscape pages, consider appropriate viewer layout") + +# Text content analysis +has_text = False +text_lines_count = 0 +total_words = 0 + +for page in info_result.pages: + if hasattr(page, 'lines') and page.lines: + has_text = True + text_lines_count += len(page.lines) + page_words = sum(len(line.words) if hasattr(line, 'words') else 0 for line in page.lines) + total_words += page_words + +if has_text: + print("\nText Content Analysis:") + print(f" - Total text lines: {text_lines_count}") + print(f" - Approximate word count: {total_words}") + print(f" - Average words per page: {total_words / len(info_result.pages):.1f}") + + # Determine if document is text-heavy + if total_words > 500: + print(" - Document is text-heavy, consider enabling text search functionality") +else: + print("\nText Content Analysis:") + print(" - No text content found or extracted") + print(" - Document may be image-based or scanned") + print(" - Consider OCR processing if text search is required") + +# Format-specific analysis +print("\nFormat-Specific Information:") + +# PDF analysis +if hasattr(info_result, 'pdf_view_info') and info_result.pdf_view_info: + print("PDF Document Properties:") + print(f" - Printing allowed: {info_result.pdf_view_info.printing_allowed}") + if not info_result.pdf_view_info.printing_allowed: + print(" - Security Note: Document has printing restrictions") + +# CAD analysis +if hasattr(info_result, 'cad_view_info') and info_result.cad_view_info: + print("CAD Drawing Properties:") + if hasattr(info_result.cad_view_info, 'layouts') and info_result.cad_view_info.layouts: + print(f" - Contains {len(info_result.cad_view_info.layouts)} layouts") + if hasattr(info_result.cad_view_info, 'layers') and info_result.cad_view_info.layers: + visible_layers = sum(1 for layer in info_result.cad_view_info.layers if layer.visible) + hidden_layers = len(info_result.cad_view_info.layers) - visible_layers + print(f" - Contains {len(info_result.cad_view_info.layers)} layers " + + f"({visible_layers} visible, {hidden_layers} hidden)") + +# Archive analysis +if hasattr(info_result, 'archive_view_info') and info_result.archive_view_info: + print("Archive Properties:") + if hasattr(info_result.archive_view_info, 'folders') and info_result.archive_view_info.folders: + print(f" - Contains {len(info_result.archive_view_info.folders)} folders") + +# Project management analysis +if hasattr(info_result, 'project_management_view_info') and info_result.project_management_view_info: + print("Project Management Properties:") + if hasattr(info_result.project_management_view_info, 'start_date'): + print(f" - Project start date: {info_result.project_management_view_info.start_date}") + if hasattr(info_result.project_management_view_info, 'end_date'): + print(f" - Project end date: {info_result.project_management_view_info.end_date}") + +# Outlook data analysis +if hasattr(info_result, 'outlook_view_info') and info_result.outlook_view_info: + print("Outlook Data Properties:") + if hasattr(info_result.outlook_view_info, 'folders') and info_result.outlook_view_info.folders: + print(f" - Contains {len(info_result.outlook_view_info.folders)} folders") + +# Final recommendations +print("\nRendering Recommendations:") +print(" - Recommended format: ", end="") +if has_text: + print("HTML (for text searchability)") +elif hasattr(info_result, 'cad_view_info') and info_result.cad_view_info: + print("PNG (for crisp lines and details)") +else: + print("PDF (for compatibility and document fidelity)") + +# Generate rendering code based on analysis +print("\nSuggested Rendering Code:") +print("python") +print("from groupdocs_viewer_cloud import ViewOptions, FileInfo") + +if has_text: + print("from groupdocs_viewer_cloud import HtmlOptions") + print("\n# Create HTML options for text searchability") + print("html_options = HtmlOptions()") + print("html_options.is_responsive = True") + + if landscape_pages > 0: + print("# Enable proper layout for landscape pages") + + if hasattr(info_result, 'cad_view_info') and info_result.cad_view_info: + print("# Configure CAD options") + print("html_options.cad_options = CadOptions()") + if info_result.cad_view_info.layouts and len(info_result.cad_view_info.layouts) > 0: + print(f"html_options.cad_options.layout_name = '{info_result.cad_view_info.layouts[0].name}'") + + print("\n# Set up view options") + print("view_options = ViewOptions()") + print("view_options.file_info = file_info") + print("view_options.view_format = 'HTML'") + print("view_options.render_options = html_options") + +elif hasattr(info_result, 'cad_view_info') and info_result.cad_view_info: + print("from groupdocs_viewer_cloud import ImageOptions, CadOptions") + print("\n# Create PNG options for CAD drawing") + print("image_options = ImageOptions()") + print("image_options.cad_options = CadOptions()") + if info_result.cad_view_info.layouts and len(info_result.cad_view_info.layouts) > 0: + print(f"image_options.cad_options.layout_name = '{info_result.cad_view_info.layouts[0].name}'") + print("image_options.width = 1200 # High resolution for details") + + print("\n# Set up view options") + print("view_options = ViewOptions()") + print("view_options.file_info = file_info") + print("view_options.view_format = 'PNG'") + print("view_options.render_options = image_options") + +else: + print("from groupdocs_viewer_cloud import PdfOptions") + print("\n# Create PDF options for general compatibility") + print("pdf_options = PdfOptions()") + + print("\n# Set up view options") + print("view_options = ViewOptions()") + print("view_options.file_info = file_info") + print("view_options.view_format = 'PDF'") + print("view_options.render_options = pdf_options") + +print("\n# Render the document") +print("result = viewer_api.view(view_options)") +print("") +``` + +## Try It Yourself + +Now that you've learned how to use InfoResult, try these exercises: + +1. Create a document analyzer that compares text density across pages to identify text-heavy sections +2. Build a CAD drawing inspector that lists all layouts and layers with their properties +3. Develop a batch processor that examines multiple documents and recommends optimal viewing settings for each + +## Troubleshooting Tips + +- Missing text content: Ensure that `extract_text` is set to `true` in your InfoOptions +- Format-specific information not available: Verify that your document is actually of the expected format +- Page dimensions are zero: Some document formats may not report dimensions until rendered +- Text extraction slow for large documents: Consider extracting text only when needed or limiting to specific pages + +## What You've Learned + +In this tutorial, you've mastered: +- How to retrieve comprehensive document information with InfoResult +- Extracting and analyzing text content from documents +- Accessing format-specific information for PDF, CAD, and other formats +- Building intelligent document analysis systems +- Creating optimal rendering settings based on document analysis + +## Next Steps + +Ready to learn how to clean up after rendering operations? Continue your learning with our [DeleteViewOptions Tutorial](/data-structures/delete-view-options) to discover how to properly manage rendered document views. + +## Helpful Resources + +- [Product Page](https://products.groupdocs.cloud/viewer/) +- [Documentation](https://docs.groupdocs.cloud/viewer/) +- [API Reference UI](https://reference.groupdocs.cloud/viewer/) +- [Free Support](https://forum.groupdocs.cloud/c/viewer/9) +- [Free Trial](https://dashboard.groupdocs.cloud/#/apps) + +Have questions about document information extraction? Post them on our [support forum](https://forum.groupdocs.cloud/c/viewer/9). diff --git a/content/viewer/english/data-structures/pdf-optimization-options/_index.md b/content/viewer/english/data-structures/pdf-optimization-options/_index.md new file mode 100644 index 0000000..8252a50 --- /dev/null +++ b/content/viewer/english/data-structures/pdf-optimization-options/_index.md @@ -0,0 +1,374 @@ +--- +title: PDF Optimization with PdfOptimizationOptions Tutorial +weight: 6 +url: /data-structures/pdf-optimization-options/ +description: Learn advanced PDF optimization techniques in this step-by-step tutorial for the PdfOptimizationOptions structure in GroupDocs.Viewer Cloud API +--- + +# Tutorial: PDF Optimization with PdfOptimizationOptions + +## Learning Objectives + +In this tutorial, you'll learn: +- How to use PdfOptimizationOptions to reduce PDF file size +- Techniques for optimizing PDFs for web viewing +- Methods for controlling image quality and resolution +- Best practices for font subsetting and other optimization approaches + +## Prerequisites + +Before starting this tutorial: +- Complete the [PdfOptions Tutorial](/data-structures/pdf-options) +- Have your GroupDocs.Viewer Cloud API credentials ready +- Prepare larger documents with images/graphics for testing + +## Introduction to PdfOptimizationOptions + +PdfOptimizationOptions is a specialized data structure used within PdfOptions to provide granular control over PDF optimization. When you need to create PDF files that are compact, web-friendly, and optimized for specific use cases, this structure gives you the tools to achieve impressive size reductions while maintaining appropriate quality. + +PDF optimization is essential for web distribution, email attachments, or any scenario where file size matters. + +## Understanding the PdfOptimizationOptions Structure + +PdfOptimizationOptions contains several key components for controlling different aspects of PDF optimization: + +- Web Optimization: Linearize PDFs for faster web viewing +- Content Removal: Remove annotations, form fields +- Image Compression: Control image quality and resolution +- Font Optimization: Subset fonts to reduce file size +- Color Conversion: Convert to grayscale +- Spreadsheet Optimization: Special optimizations for spreadsheet content + +Let's explore these options with practical examples. + +## Tutorial Steps + +### Step 1: Basic PDF Optimization Setup + +Let's start with a basic optimization configuration: + +```python +# Tutorial Code Example: Basic PDF optimization +import os +from groupdocs_viewer_cloud import Configuration, ViewerApi, ViewOptions, PdfOptions, PdfOptimizationOptions, FileInfo + +# Configure the API client +configuration = Configuration(client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET") +viewer_api = ViewerApi.from_config(configuration) + +# Set up file info +file_info = FileInfo() +file_info.file_path = "documents/large-report.docx" + +# Create PDF optimization options +optimization_options = PdfOptimizationOptions() +# We'll start with default settings and build up + +# Set optimization options in PdfOptions +pdf_options = PdfOptions() +pdf_options.pdf_optimization_options = optimization_options + +# Set up view options +view_options = ViewOptions() +view_options.file_info = file_info +view_options.view_format = "PDF" +view_options.render_options = pdf_options +view_options.output_path = "output/basic-optimized.pdf" + +# Render the document +result = viewer_api.view(view_options) + +print(f"Document rendered to PDF with basic optimization") +print(f"PDF file path: {result.file}") +``` + +### Step 2: Optimizing for Web Viewing + +For PDFs intended for web distribution, linearization significantly improves viewing experience: + +```python +# Tutorial Code Example: Web optimization with linearization +from groupdocs_viewer_cloud import ViewOptions, PdfOptions, PdfOptimizationOptions, FileInfo + +# Set up file info +file_info = FileInfo() +file_info.file_path = "documents/annual-report.pptx" + +# Create web-optimized PDF options +optimization_options = PdfOptimizationOptions() +optimization_options.lineriaze = True # Enable linearization for web viewing +# Note: The API property is spelled "lineriaze" (with an 'i') + +# Set optimization options in PdfOptions +pdf_options = PdfOptions() +pdf_options.pdf_optimization_options = optimization_options + +# Set up view options +view_options = ViewOptions() +view_options.file_info = file_info +view_options.view_format = "PDF" +view_options.render_options = pdf_options +view_options.output_path = "output/web-optimized.pdf" + +# Render the document +result = viewer_api.view(view_options) + +print(f"Document rendered to web-optimized PDF") +print(f"The linearized PDF will load progressively in web browsers") +print(f"Users can see the first pages while the rest of the document is still loading") +``` + +### Step 3: Image Compression Optimization + +Many PDFs are large because of embedded images. Here's how to optimize them: + +```python +# Tutorial Code Example: Image compression optimization +from groupdocs_viewer_cloud import ViewOptions, PdfOptions, PdfOptimizationOptions, FileInfo + +# Set up file info +file_info = FileInfo() +file_info.file_path = "documents/image-heavy-brochure.pdf" + +# Create image-optimized PDF options +optimization_options = PdfOptimizationOptions() +optimization_options.compress_images = True # Enable image compression +optimization_options.image_quality = 75 # Set quality percentage (lower = smaller file) +optimization_options.resize_images = True # Allow resizing of images +optimization_options.max_resolution = 220 # Max resolution in DPI (lower = smaller images) + +# Set optimization options in PdfOptions +pdf_options = PdfOptions() +pdf_options.pdf_optimization_options = optimization_options + +# Set up view options +view_options = ViewOptions() +view_options.file_info = file_info +view_options.view_format = "PDF" +view_options.render_options = pdf_options +view_options.output_path = "output/image-optimized.pdf" + +# Render the document +result = viewer_api.view(view_options) + +print(f"Document rendered to PDF with optimized images") +print(f"Image compression and resolution limits significantly reduce file size") +``` + +### Step 4: Font Subsetting for Size Reduction + +Embedded fonts can significantly increase PDF size. Font subsetting helps: + +```python +# Tutorial Code Example: Font subsetting optimization +from groupdocs_viewer_cloud import ViewOptions, PdfOptions, PdfOptimizationOptions, FileInfo + +# Set up file info +file_info = FileInfo() +file_info.file_path = "documents/custom-font-document.docx" + +# Create font-optimized PDF options +optimization_options = PdfOptimizationOptions() +optimization_options.subset_fonts = True # Enable font subsetting + +# Set optimization options in PdfOptions +pdf_options = PdfOptions() +pdf_options.pdf_optimization_options = optimization_options + +# Set up view options +view_options = ViewOptions() +view_options.file_info = file_info +view_options.view_format = "PDF" +view_options.render_options = pdf_options +view_options.output_path = "output/font-optimized.pdf" + +# Render the document +result = viewer_api.view(view_options) + +print(f"Document rendered to PDF with font subsetting") +print(f"Only the characters used in the document are included in the embedded fonts") +``` + +### Step 5: Grayscale Conversion + +Converting color content to grayscale can dramatically reduce file size: + +```python +# Tutorial Code Example: Grayscale conversion +from groupdocs_viewer_cloud import ViewOptions, PdfOptions, PdfOptimizationOptions, FileInfo + +# Set up file info +file_info = FileInfo() +file_info.file_path = "documents/colorful-presentation.pptx" + +# Create grayscale PDF options +optimization_options = PdfOptimizationOptions() +optimization_options.convert_to_gray_scale = True # Convert to grayscale + +# Set optimization options in PdfOptions +pdf_options = PdfOptions() +pdf_options.pdf_optimization_options = optimization_options + +# Set up view options +view_options = ViewOptions() +view_options.file_info = file_info +view_options.view_format = "PDF" +view_options.render_options = pdf_options +view_options.output_path = "output/grayscale-document.pdf" + +# Render the document +result = viewer_api.view(view_options) + +print(f"Document rendered to grayscale PDF") +print(f"Color conversion dramatically reduces file size") +print(f"Ideal for documents that will be printed in black and white") +``` + +### Step 6: Content Removal Optimization + +You can reduce file size by removing non-essential content: + +```python +# Tutorial Code Example: Content removal optimization +from groupdocs_viewer_cloud import ViewOptions, PdfOptions, PdfOptimizationOptions, FileInfo + +# Set up file info +file_info = FileInfo() +file_info.file_path = "documents/annotated-form.pdf" + +# Create content-optimized PDF options +optimization_options = PdfOptimizationOptions() +optimization_options.remove_annotations = True # Remove annotations +optimization_options.remove_form_fields = True # Remove form fields + +# Set optimization options in PdfOptions +pdf_options = PdfOptions() +pdf_options.pdf_optimization_options = optimization_options + +# Set up view options +view_options = ViewOptions() +view_options.file_info = file_info +view_options.view_format = "PDF" +view_options.render_options = pdf_options +view_options.output_path = "output/content-optimized.pdf" + +# Render the document +result = viewer_api.view(view_options) + +print(f"Document rendered to PDF with non-essential content removed") +print(f"Annotations and form fields have been removed to reduce size") +``` + +### Step 7: Spreadsheet-Specific Optimization + +Spreadsheets can benefit from special optimization techniques: + +```python +# Tutorial Code Example: Spreadsheet optimization +from groupdocs_viewer_cloud import ViewOptions, PdfOptions, PdfOptimizationOptions, FileInfo + +# Set up file info +file_info = FileInfo() +file_info.file_path = "documents/financial-spreadsheet.xlsx" + +# Create spreadsheet-optimized PDF options +optimization_options = PdfOptimizationOptions() +optimization_options.optimize_spreadsheets = True # Enable spreadsheet optimization + +# Set optimization options in PdfOptions +pdf_options = PdfOptions() +pdf_options.pdf_optimization_options = optimization_options + +# Set up view options +view_options = ViewOptions() +view_options.file_info = file_info +view_options.view_format = "PDF" +view_options.render_options = pdf_options +view_options.output_path = "output/spreadsheet-optimized.pdf" + +# Render the document +result = viewer_api.view(view_options) + +print(f"Spreadsheet rendered to optimized PDF") +print(f"Special optimizations applied for spreadsheet content") +``` + +### Step 8: Comprehensive Optimization Strategy + +Let's combine multiple optimization techniques for maximum effect: + +```python +# Tutorial Code Example: Comprehensive optimization strategy +from groupdocs_viewer_cloud import ViewOptions, PdfOptions, PdfOptimizationOptions, FileInfo + +# Set up file info +file_info = FileInfo() +file_info.file_path = "documents/large-annual-report.pptx" + +# Create comprehensive optimization options +optimization_options = PdfOptimizationOptions() +optimization_options.lineriaze = True # Web optimization +optimization_options.compress_images = True # Image compression +optimization_options.image_quality = 80 # Good balance of quality and size +optimization_options.resize_images = True # Allow image resizing +optimization_options.max_resolution = 150 # Lower resolution for web viewing +optimization_options.subset_fonts = True # Font subsetting +optimization_options.remove_annotations = True # Remove annotations +optimization_options.remove_form_fields = True # Remove form fields + +# Set optimization options in PdfOptions +pdf_options = PdfOptions() +pdf_options.pdf_optimization_options = optimization_options + +# Set up view options +view_options = ViewOptions() +view_options.file_info = file_info +view_options.view_format = "PDF" +view_options.render_options = pdf_options +view_options.output_path = "output/fully-optimized.pdf" + +# Render the document +result = viewer_api.view(view_options) + +print(f"Document rendered to fully optimized PDF") +print(f"Applied comprehensive optimization strategy for maximum size reduction") +print(f"Resulting PDF is web-friendly with significantly reduced file size") +``` + +## Try It Yourself + +Now that you've learned how to use PdfOptimizationOptions, try these exercises: + +1. Optimize a large presentation with many images (target a 70% size reduction) +2. Create a print-optimized PDF by converting to grayscale and removing non-essential content +3. Compare file sizes between different optimization strategies to determine the most effective approach for your specific document types + +## Troubleshooting Tips + +- Quality too low: If image quality is poor, increase the `image_quality` value +- File still too large: Try more aggressive settings, particularly lower `max_resolution` and `image_quality` +- Missing content: If important content is missing, check if you're removing annotations or form fields that contain valuable information +- Font issues: If fonts appear inconsistent after subsetting, you may need to disable font subsetting for that particular document + +## What You've Learned + +In this tutorial, you've mastered: +- How to implement web optimization for faster loading PDFs +- Techniques for compressing and resizing images within documents +- Methods for font subsetting to reduce embedded font size +- Strategies for removing non-essential content +- How to create comprehensive optimization profiles for different document types + +## Next Steps + +Ready to explore how to process the output from the Viewer API? Continue with our [ViewResult Tutorial](/data-structures/view-result) to learn how to effectively handle the rendering results. + +## Helpful Resources + +- [Product Page](https://products.groupdocs.cloud/viewer/) +- [Documentation](https://docs.groupdocs.cloud/viewer/) +- [API Reference UI](https://reference.groupdocs.cloud/viewer/) +- [Free Support](https://forum.groupdocs.cloud/c/viewer/9) +- [Free Trial](https://dashboard.groupdocs.cloud/#/apps) + +Have questions about PDF optimization? Post them on our [support forum](https://forum.groupdocs.cloud/c/viewer/9). diff --git a/content/viewer/english/data-structures/render-options/_index.md b/content/viewer/english/data-structures/render-options/_index.md new file mode 100644 index 0000000..fa39209 --- /dev/null +++ b/content/viewer/english/data-structures/render-options/_index.md @@ -0,0 +1,340 @@ +--- +title: Controlling Document Rendering with RenderOptions Tutorial +weight: 2 +url: /data-structures/render-options/ +description: Learn how to master document rendering controls with this RenderOptions tutorial for GroupDocs.Viewer Cloud API +--- + +# Tutorial: Controlling Document Rendering with RenderOptions + +## Learning Objectives + +In this tutorial, you'll learn: +- How to use RenderOptions to control document rendering behavior +- Techniques for page selection, rotation, and formatting +- Format-specific rendering options for spreadsheets, CAD drawings, and more +- How to optimize rendered outputs for different document types + +## Prerequisites + +Before starting this tutorial: +- Complete the [ViewOptions Tutorial](/data-structures/view-options/) +- Have your GroupDocs.Viewer Cloud API credentials ready +- Prepare various test documents (spreadsheets, word documents, PDF files) + +## Introduction to RenderOptions + +RenderOptions is a powerful data structure that gives you fine-grained control over how documents are rendered in GroupDocs.Viewer Cloud. While ViewOptions handles the overall configuration, RenderOptions focuses specifically on the rendering process and appearance. + +This data structure allows you to specify which pages to render, control page rotation, set default fonts, and configure format-specific rendering behaviors. + +## Understanding the RenderOptions Structure + +RenderOptions contains several key components: + +- Page Selection Options: Control which pages are rendered +- Appearance Options: Configure fonts, encoding, and comments +- Format-Specific Options: Special settings for spreadsheets, CAD files, emails, etc. + +Let's explore how to use these components effectively in real-world scenarios. + +## Tutorial Steps + +### Step 1: Basic Page Selection + +One of the most common requirements is to render specific pages rather than the entire document: + +```python +# Tutorial Code Example: Page selection with RenderOptions +import os +from groupdocs_viewer_cloud import Configuration, ViewerApi, ViewOptions, HtmlOptions, FileInfo + +# Configure the API client +configuration = Configuration(client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET") +viewer_api = ViewerApi.from_config(configuration) + +# Set up file info +file_info = FileInfo() +file_info.file_path = "documents/large-document.pdf" + +# Create HTML options with page selection +html_options = HtmlOptions() +# Method 1: Start page and count +html_options.start_page_number = 5 # Start from page 5 +html_options.count_pages_to_render = 3 # Render 3 pages total (5, 6, and 7) + +# Method 2: Specific pages list +# Uncomment to use this method instead +# html_options.pages_to_render = [2, 5, 9] # Only render pages 2, 5, and 9 + +# Set up view options +view_options = ViewOptions() +view_options.file_info = file_info +view_options.view_format = "HTML" +view_options.render_options = html_options + +# Render the document +result = viewer_api.view(view_options) + +print(f"Rendered {len(result.pages)} pages from the document") +for page in result.pages: + print(f"Page {page.number} path: {page.path}") +``` + +### Step 2: Page Rotation + +Sometimes you need to rotate pages for better viewing, especially for landscape documents: + +```python +# Tutorial Code Example: Page rotation with RenderOptions +from groupdocs_viewer_cloud import ViewOptions, HtmlOptions, PageRotation + +# Set up file info +file_info = FileInfo() +file_info.file_path = "documents/landscape-document.pdf" + +# Create rotation settings for specific pages +page_rotations = [] + +# Create rotation for page 1 - rotate 90 degrees +rotation1 = PageRotation() +rotation1.page_number = 1 # First page +rotation1.rotation_angle = "On90Degree" # 90-degree rotation +page_rotations.append(rotation1) + +# Create rotation for page 2 - rotate 180 degrees +rotation2 = PageRotation() +rotation2.page_number = 2 # Second page +rotation2.rotation_angle = "On180Degree" # 180-degree rotation +page_rotations.append(rotation2) + +# Configure HTML options with rotations +html_options = HtmlOptions() +html_options.page_rotations = page_rotations + +# Set up view options +view_options = ViewOptions() +view_options.file_info = file_info +view_options.view_format = "HTML" +view_options.render_options = html_options + +# Render the document +result = viewer_api.view(view_options) + +print(f"Document rendered with page rotations applied") +``` + +### Step 3: Working with Spreadsheets + +Spreadsheets have unique rendering requirements. Here's how to optimize their rendering: + +```python +# Tutorial Code Example: Spreadsheet rendering options +from groupdocs_viewer_cloud import ViewOptions, HtmlOptions, SpreadsheetOptions + +# Set up file info +file_info = FileInfo() +file_info.file_path = "documents/financial-report.xlsx" + +# Configure spreadsheet-specific options +html_options = HtmlOptions() +html_options.spreadsheet_options = SpreadsheetOptions() +html_options.spreadsheet_options.paginate_sheets = True # Split sheets into pages +html_options.spreadsheet_options.count_rows_per_page = 40 # Rows per page +html_options.spreadsheet_options.render_grid_lines = True # Show gridlines +html_options.spreadsheet_options.render_headings = True # Show row/column headings +html_options.spreadsheet_options.render_empty_rows = False # Skip empty rows +html_options.spreadsheet_options.render_hidden_columns = False # Skip hidden columns + +# Set up view options +view_options = ViewOptions() +view_options.file_info = file_info +view_options.view_format = "HTML" +view_options.render_options = html_options + +# Render the spreadsheet +result = viewer_api.view(view_options) + +print(f"Spreadsheet rendered with pagination: {len(result.pages)} pages created") +``` + +### Step 4: Rendering CAD Drawings + +CAD drawings require special handling for proper rendering: + +```python +# Tutorial Code Example: CAD rendering options +from groupdocs_viewer_cloud import ViewOptions, PngOptions, CadOptions + +# Set up file info +file_info = FileInfo() +file_info.file_path = "documents/engineering-drawing.dwg" + +# Configure CAD-specific options +png_options = PngOptions() +png_options.cad_options = CadOptions() +png_options.cad_options.scale_factor = 1.5 # Increase scale by 50% +png_options.cad_options.width = 1200 # Output width in pixels +png_options.cad_options.height = 800 # Output height in pixels + +# Specify layers to render (leave empty for all layers) +png_options.cad_options.layers = ["Layer1", "Dimensions"] + +# Set up view options +view_options = ViewOptions() +view_options.file_info = file_info +view_options.view_format = "PNG" +view_options.render_options = png_options + +# Render the CAD drawing +result = viewer_api.view(view_options) + +print(f"CAD drawing rendered to PNG images: {len(result.pages)} pages") +``` + +### Step 5: Email Document Rendering + +Email documents have their own specific formatting needs: + +```python +# Tutorial Code Example: Email rendering options +from groupdocs_viewer_cloud import ViewOptions, HtmlOptions, EmailOptions, Field, FieldLabel + +# Set up file info +file_info = FileInfo() +file_info.file_path = "documents/business-email.eml" + +# Create custom field labels +field_labels = [] + +# Customize "From" field label +from_field = FieldLabel() +from_field.field = "From" +from_field.label = "Sender" +field_labels.append(from_field) + +# Customize "To" field label +to_field = FieldLabel() +to_field.field = "To" +to_field.label = "Recipients" +field_labels.append(to_field) + +# Configure email-specific options +html_options = HtmlOptions() +html_options.email_options = EmailOptions() +html_options.email_options.field_labels = field_labels +html_options.email_options.date_time_format = "MMM d, yyyy 'at' h:mm tt" +html_options.email_options.time_zone_offset = "+01:00" # GMT+1 + +# Set up view options +view_options = ViewOptions() +view_options.file_info = file_info +view_options.view_format = "HTML" +view_options.render_options = html_options + +# Render the email +result = viewer_api.view(view_options) + +print(f"Email document rendered with custom field labels") +``` + +### Step 6: PDF Document Rendering Options + +PDF documents can be rendered with specific options for better quality and performance: + +```python +# Tutorial Code Example: PDF rendering options +from groupdocs_viewer_cloud import ViewOptions, HtmlOptions, PdfDocumentOptions + +# Set up file info +file_info = FileInfo() +file_info.file_path = "documents/technical-specification.pdf" + +# Configure PDF-specific options +html_options = HtmlOptions() +html_options.pdf_document_options = PdfDocumentOptions() +html_options.pdf_document_options.disable_chars_grouping = True # Better text positioning +html_options.pdf_document_options.enable_layered_rendering = True # Respect z-order +html_options.pdf_document_options.image_quality = "High" # High quality images +html_options.pdf_document_options.render_text_as_image = False # Keep text selectable + +# Set up view options +view_options = ViewOptions() +view_options.file_info = file_info +view_options.view_format = "HTML" +view_options.render_options = html_options + +# Render the PDF +result = viewer_api.view(view_options) + +print(f"PDF document rendered with enhanced options: {len(result.pages)} pages") +``` + +### Step 7: Word Processing Document Options + +Word documents can be rendered with these specialized options: + +```python +# Tutorial Code Example: Word document rendering options +from groupdocs_viewer_cloud import ViewOptions, HtmlOptions, WordProcessingOptions + +# Set up file info +file_info = FileInfo() +file_info.file_path = "documents/contract-with-changes.docx" + +# Configure Word-specific options +html_options = HtmlOptions() +html_options.word_processing_options = WordProcessingOptions() +html_options.word_processing_options.render_tracked_changes = True # Show track changes +html_options.word_processing_options.left_margin = 50 # Left margin in points +html_options.word_processing_options.right_margin = 50 # Right margin in points +html_options.word_processing_options.top_margin = 40 # Top margin in points +html_options.word_processing_options.bottom_margin = 40 # Bottom margin in points + +# Set up view options +view_options = ViewOptions() +view_options.file_info = file_info +view_options.view_format = "HTML" +view_options.render_options = html_options + +# Render the Word document +result = viewer_api.view(view_options) + +print(f"Word document rendered with tracked changes visible") +``` + +## Try It Yourself + +Now that you've learned how to use RenderOptions for different document types, try these exercises: + +1. Render a spreadsheet showing only the print area +2. Create a rendering of a PDF document with text rendered as images for copy protection +3. Implement page rotation for a multi-page document where odd pages are rotated 90 degrees + +## Troubleshooting Tips + +- Format-specific options not applied: Make sure you're using the right format-specific option for your document type +- Page selection issues: Verify that page numbers start from 1, not 0 +- Missing content in spreadsheets: Check if hidden rows/columns are being skipped with the rendering options + +## What You've Learned + +In this tutorial, you've mastered: +- How to select specific pages for rendering +- Techniques for rotating pages to improve document viewing +- Format-specific rendering for spreadsheets, CAD drawings, emails, and more +- Advanced options for optimizing rendered output quality + +## Next Steps + +Ready to learn more about format-specific rendering? Continue your journey with our [HTML Rendering Tutorial](/data-structures/htmloptions) or [Image Rendering Tutorial](/data-structures/image-options/). + +## Helpful Resources + +- [Product Page](https://products.groupdocs.cloud/viewer/) +- [Documentation](https://docs.groupdocs.cloud/viewer/) +- [API Reference UI](https://reference.groupdocs.cloud/viewer/) +- [Free Support](https://forum.groupdocs.cloud/c/viewer/9) +- [Free Trial](https://dashboard.groupdocs.cloud/#/apps) + +Have questions about configuring RenderOptions? Post them on our [support forum](https://forum.groupdocs.cloud/c/viewer/9). diff --git a/content/viewer/english/data-structures/view-options/_index.md b/content/viewer/english/data-structures/view-options/_index.md new file mode 100644 index 0000000..9dc5e81 --- /dev/null +++ b/content/viewer/english/data-structures/view-options/_index.md @@ -0,0 +1,253 @@ +--- +title: How to Use ViewOptions with GroupDocs.Viewer Cloud API Tutorial +url: /data-structures/view-options/ +weight: 1 +description: Learn how to configure document viewing options in this step-by-step tutorial for the ViewOptions data structure in GroupDocs.Viewer Cloud API +--- + +# Tutorial: How to Use ViewOptions with GroupDocs.Viewer Cloud API + +## Learning Objectives + +In this tutorial, you'll learn: +- What the ViewOptions data structure is and why it's important +- How to configure basic viewing settings for different document formats +- Step-by-step implementation for HTML, Image, and PDF rendering +- How to apply watermarks and customize output paths + +## Prerequisites + +Before starting this tutorial: +- Create a [GroupDocs Cloud account](https://dashboard.groupdocs.cloud) and get your Client ID and Client Secret +- Have basic knowledge of RESTful API concepts +- Prepare a sample document for testing (DOCX, PDF, XLSX, etc.) + +## Introduction to ViewOptions + +The ViewOptions data structure is the foundation of document rendering in GroupDocs.Viewer Cloud. It provides the configuration needed to specify how your documents should be rendered, including format, security options, watermarks, and output settings. + +Think of ViewOptions as your document rendering instruction set - it tells the API exactly how you want your document processed and displayed. + +## Understanding the ViewOptions Structure + +The ViewOptions data structure has several key components: + +- ViewFormat: Determines the output format (HTML, JPG, PNG, or PDF) +- FileInfo: Contains source document information (path, password, etc.) +- OutputPath: Defines where rendered results will be stored +- Watermark: Settings for applying text watermarks +- RenderOptions: Format-specific rendering settings + +Let's explore how to use these components in practical scenarios. + +## Tutorial Steps + +### Step 1: Set Up Your Environment + +First, let's prepare our environment by configuring the API client with your credentials: + +```python +# Tutorial Code Example: Setting up GroupDocs.Viewer Cloud API client +import os +from groupdocs_viewer_cloud import Configuration, ViewerApi, FileInfo + +# Set your App SID and App Key +configuration = Configuration(client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET") +viewer_api = ViewerApi.from_config(configuration) + +print("API client configured successfully") +``` + +### Step 2: Creating Basic ViewOptions for HTML Rendering + +Let's start with the most common use case - rendering a document to HTML: + +```python +# Tutorial Code Example: Basic HTML rendering with ViewOptions +from groupdocs_viewer_cloud import ViewOptions, HtmlOptions + +# Create FileInfo object +file_info = FileInfo() +file_info.file_path = "documents/sample.docx" # Document in your cloud storage +file_info.password = "" # Set if document is password-protected + +# Create view options +view_options = ViewOptions() +view_options.file_info = file_info +view_options.view_format = "HTML" # Set output format to HTML +view_options.render_options = HtmlOptions() # Use HTML-specific options + +# Run the rendering operation and get the result +result = viewer_api.view(view_options) + +print(f"Document rendered to HTML successfully. Pages: {len(result.pages)}") +for page in result.pages: + print(f"Page {page.number} available at: {page.path}") +``` + +### Step 3: Customizing Output with External Resources + +When rendering to HTML, you might want to separate resources (images, fonts) from the HTML content: + +```python +# Tutorial Code Example: HTML rendering with external resources +from groupdocs_viewer_cloud import ViewOptions, HtmlOptions + +# Setup file info +file_info = FileInfo() +file_info.file_path = "documents/presentation.pptx" + +# Configure HTML-specific options +html_options = HtmlOptions() +html_options.external_resources = True # Extract resources as separate files +html_options.resource_path = "viewer/resources/{resource-name}" # Template for resource paths +html_options.is_responsive = True # Make output responsive for different screens + +# Set up view options with our HTML configuration +view_options = ViewOptions() +view_options.file_info = file_info +view_options.view_format = "HTML" +view_options.render_options = html_options +view_options.output_path = "output/presentation_html" # Custom output folder + +# Render the document +result = viewer_api.view(view_options) + +print(f"Responsive HTML with external resources created successfully") +# Now you can see the resource paths in the result +for page in result.pages: + print(f"Page {page.number} resources count: {len(page.resources)}") +``` + +### Step 4: Rendering to Images (JPG/PNG) + +For some use cases, you might need to convert documents to images instead of HTML: + +```python +# Tutorial Code Example: Image rendering with ViewOptions +from groupdocs_viewer_cloud import ViewOptions, ImageOptions + +# Setup file info +file_info = FileInfo() +file_info.file_path = "documents/contract.pdf" + +# Configure image-specific options +image_options = ImageOptions() +image_options.width = 800 # Set output width in pixels +image_options.height = 0 # Height will be calculated automatically to maintain aspect ratio +image_options.jpeg_quality = 90 # Set quality for JPG output (1-100) +image_options.extract_text = True # Extract text to enable search in images + +# Set up view options with our image configuration +view_options = ViewOptions() +view_options.file_info = file_info +view_options.view_format = "JPG" # Can also use "PNG" +view_options.render_options = image_options +view_options.output_path = "output/contract_images" + +# Render the document +result = viewer_api.view(view_options) + +print(f"Document rendered to JPG images: {len(result.pages)} pages created") +``` + +### Step 5: Creating PDF Output with Watermarks + +PDF output is ideal for creating distributable documents with watermarks: + +```python +# Tutorial Code Example: PDF rendering with watermark +from groupdocs_viewer_cloud import ViewOptions, PdfOptions, Watermark + +# Setup file info +file_info = FileInfo() +file_info.file_path = "documents/spreadsheet.xlsx" + +# Configure watermark +watermark = Watermark() +watermark.text = "CONFIDENTIAL" +watermark.color = "(255,0,0,50)" # Red with 50% opacity +watermark.position = "Diagonal" +watermark.size = 75 # Size in percentage + +# Configure PDF options +pdf_options = PdfOptions() +# No special PDF settings for now - we'll use defaults + +# Set up view options +view_options = ViewOptions() +view_options.file_info = file_info +view_options.view_format = "PDF" +view_options.render_options = pdf_options +view_options.watermark = watermark +view_options.output_path = "output/spreadsheet.pdf" + +# Render the document +result = viewer_api.view(view_options) + +print(f"PDF created with watermark: {result.file}") +``` + +### Step 6: Working with Password-Protected Documents + +For secured documents, you'll need to provide the password in the FileInfo section: + +```python +# Tutorial Code Example: Working with password-protected documents +from groupdocs_viewer_cloud import ViewOptions, HtmlOptions + +# Setup file info with password +file_info = FileInfo() +file_info.file_path = "documents/protected_document.docx" +file_info.password = "your_document_password" # Password to open the document + +# Configure view options +view_options = ViewOptions() +view_options.file_info = file_info +view_options.view_format = "HTML" +view_options.render_options = HtmlOptions() + +# Try to render the document +try: + result = viewer_api.view(view_options) + print(f"Password-protected document rendered successfully: {len(result.pages)} pages") +except Exception as e: + print(f"Error: {str(e)}") + # If wrong password, you'll get an error here +``` + +## Try It Yourself + +Now that you've learned the basics of ViewOptions, try these exercises to reinforce your knowledge: + +1. Render a multi-page document and limit the output to only pages 2-4 +2. Apply a custom watermark with your company name positioned at the bottom right +3. Render a document to responsive HTML with external resources + +## Troubleshooting Tips + +- Error: Document not found: Ensure the file path is correct and the document exists in your cloud storage +- Error: Invalid password: Double-check the document password is correct +- Missing resources in HTML output: Verify that `external_resources` is set to `true` and check the `resource_path` format + +## What You've Learned + +In this tutorial, you've learned: +- How to configure the ViewOptions data structure for different output formats +- Techniques for customizing HTML, image, and PDF output +- How to apply watermarks to rendered documents +- Methods for handling password-protected files + +## Next Steps + +Ready to dive deeper? Continue your learning journey with our [RenderOptions Tutorial](/data-structures/render-options) to explore advanced rendering configuration options. + +## Helpful Resources + +- [Product Page](https://products.groupdocs.cloud/viewer/) +- [Documentation](https://docs.groupdocs.cloud/viewer/) +- [API Reference UI](https://reference.groupdocs.cloud/viewer/) +- [Free Support](https://forum.groupdocs.cloud/c/viewer/9) +- [Free Trial](https://dashboard.groupdocs.cloud/#/apps) + +Have questions about this tutorial? Feel free to post them on our [support forum](https://forum.groupdocs.cloud/c/viewer/9). diff --git a/content/viewer/english/data-structures/view-result/_index.md b/content/viewer/english/data-structures/view-result/_index.md new file mode 100644 index 0000000..af5880a --- /dev/null +++ b/content/viewer/english/data-structures/view-result/_index.md @@ -0,0 +1,572 @@ +--- +title: Working with ViewResult Tutorial +url: /data-structures/view-result/ +weight: 7 +description: Learn how to process and utilize the output from document rendering in this step-by-step ViewResult tutorial for GroupDocs.Viewer Cloud API +--- + +# Tutorial: Working with ViewResult + +## Learning Objectives + +In this tutorial, you'll learn: +- What the ViewResult data structure contains after document rendering +- How to access and process rendered pages and resources +- Techniques for building UI components with ViewResult data +- Methods for downloading and utilizing rendered content + +## Prerequisites + +Before starting this tutorial: +- Complete the [ViewOptions Tutorial](/data-structures/view-options/) +- Have your GroupDocs.Viewer Cloud API credentials ready +- Understand basic document rendering concepts + +## Introduction to ViewResult + +The ViewResult data structure is what you receive after calling the Document View API. It contains all the information about the rendered output, including references to rendered pages, resources, and attachments. Understanding this structure is essential for building document viewing applications that effectively utilize the GroupDocs.Viewer Cloud API. + +Think of ViewResult as your roadmap to the rendered content - it tells you where to find each piece of the rendered document and provides the information needed to display them correctly. + +## Understanding the ViewResult Structure + +ViewResult contains several key components: + +- pages: List of rendered document pages with their metadata +- attachments: List of document attachments (if any) +- file: Path to the output PDF file (when rendering to PDF format) + +Let's explore these components with practical examples. + +## Tutorial Steps + +### Step 1: Rendering a Document and Examining ViewResult + +Let's start by rendering a document and examining the ViewResult structure: + +```python +# Tutorial Code Example: Basic ViewResult examination +import os +from groupdocs_viewer_cloud import Configuration, ViewerApi, ViewOptions, HtmlOptions, FileInfo + +# Configure the API client +configuration = Configuration(client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET") +viewer_api = ViewerApi.from_config(configuration) + +# Set up file info +file_info = FileInfo() +file_info.file_path = "documents/sample.docx" + +# Create HTML options +html_options = HtmlOptions() + +# Set up view options +view_options = ViewOptions() +view_options.file_info = file_info +view_options.view_format = "HTML" +view_options.render_options = html_options +view_options.output_path = "output/sample_html" + +# Render the document and get ViewResult +result = viewer_api.view(view_options) + +# Examine the ViewResult structure +print(f"ViewResult contains {len(result.pages)} pages") +if result.pages: + print("\nFirst page information:") + page = result.pages[0] + print(f" - Page number: {page.number}") + print(f" - Path: {page.path}") + print(f" - Download URL: {page.download_url}") + print(f" - Resources count: {len(page.resources)}") + +# Check if there are any attachments +if result.attachments: + print(f"\nDocument has {len(result.attachments)} attachments") + for attachment in result.attachments: + print(f" - {attachment.name}") +``` + +### Step 2: Working with HTML Page Output + +When rendering to HTML format, you'll receive pages that can be displayed in a web browser: + +```python +# Tutorial Code Example: Processing HTML ViewResult +from groupdocs_viewer_cloud import ViewOptions, HtmlOptions, FileInfo + +# Set up file info +file_info = FileInfo() +file_info.file_path = "documents/multi-page.pdf" + +# Create HTML options with external resources +html_options = HtmlOptions() +html_options.external_resources = True + +# Set up view options +view_options = ViewOptions() +view_options.file_info = file_info +view_options.view_format = "HTML" +view_options.render_options = html_options +view_options.output_path = "output/multipage_html" + +# Render the document +result = viewer_api.view(view_options) + +# Process the HTML pages +print(f"Document rendered to {len(result.pages)} HTML pages") +for page in result.pages: + print(f"\nPage {page.number}:") + print(f" - Path: {page.path}") + print(f" - Download URL: {page.download_url}") + + # Process external resources + if page.resources: + print(f" - Resources ({len(page.resources)}):") + for resource in page.resources[:3]: # Show first 3 resources + print(f" * {resource.name} - {resource.path}") + if len(page.resources) > 3: + print(f" * ... and {len(page.resources) - 3} more resources") + +# Generate code for a simple viewer using the results +print("\nExample HTML code for a basic viewer:") +print("html") +print("
") +print(" ") +print("
") +print("
") +print("") +print("") +print("") +``` + +### Step 3: Working with Image Output + +When rendering to image formats (JPG/PNG), the ViewResult structure is similar: + +```python +# Tutorial Code Example: Processing Image ViewResult +from groupdocs_viewer_cloud import ViewOptions, ImageOptions, FileInfo + +# Set up file info +file_info = FileInfo() +file_info.file_path = "documents/presentation.pptx" + +# Create image options +image_options = ImageOptions() +image_options.width = 800 # Set width for better viewing + +# Set up view options +view_options = ViewOptions() +view_options.file_info = file_info +view_options.view_format = "PNG" # PNG for better quality +view_options.render_options = image_options +view_options.output_path = "output/presentation_images" + +# Render the document +result = viewer_api.view(view_options) + +# Process the image pages +print(f"Presentation rendered to {len(result.pages)} PNG images") +for page in result.pages: + print(f"\nSlide {page.number}:") + print(f" - Path: {page.path}") + print(f" - Download URL: {page.download_url}") + +# Generate code for an image gallery viewer +print("\nExample JavaScript code for an image gallery viewer:") +print("javascript") +print("const slides = [") +for page in result.pages: + print(f" {{") + print(f" number: {page.number},") + print(f" url: '{page.download_url}'") + print(f" }},") +print("];") +print("") +print("let currentSlide = 0;") +print("") +print("function renderGallery() {") +print(" const gallery = document.getElementById('presentation-gallery');") +print(" gallery.innerHTML = '';") +print("") +print(" // Create thumbnails") +print(" slides.forEach((slide, index) => {") +print(" const thumbnail = document.createElement('div');") +print(" thumbnail.className = 'thumbnail';") +print(" if (index === currentSlide) {") +print(" thumbnail.className += ' active';") +print(" }") +print("") +print(" const img = document.createElement('img');") +print(" img.src = slide.url;") +print(" img.alt = `Slide ${slide.number}`;") +print(" img.onclick = () => {") +print(" currentSlide = index;") +print(" showCurrentSlide();") +print(" renderGallery();") +print(" };") +print("") +print(" thumbnail.appendChild(img);") +print(" gallery.appendChild(thumbnail);") +print(" });") +print("}") +print("") +print("function showCurrentSlide() {") +print(" const mainViewer = document.getElementById('main-viewer');") +print(" mainViewer.src = slides[currentSlide].url;") +print(" document.getElementById('slide-number').textContent = slides[currentSlide].number;") +print("}") +print("") +print("function nextSlide() {") +print(" if (currentSlide < slides.length - 1) {") +print(" currentSlide++;") +print(" showCurrentSlide();") +print(" renderGallery();") +print(" }") +print("}") +print("") +print("function prevSlide() {") +print(" if (currentSlide > 0) { + currentSlide--; + showCurrentSlide(); + renderGallery(); + } +} + +// Initialize the viewer +document.addEventListener('DOMContentLoaded', () => { + showCurrentSlide(); + renderGallery(); +}); +``` + +### Step 4: Working with PDF Output + +When rendering to PDF format, the ViewResult structure is different and contains a file path instead of pages: + +```python +# Tutorial Code Example: Processing PDF ViewResult +from groupdocs_viewer_cloud import ViewOptions, PdfOptions, FileInfo + +# Set up file info +file_info = FileInfo() +file_info.file_path = "documents/contract.docx" + +# Create PDF options +pdf_options = PdfOptions() + +# Set up view options +view_options = ViewOptions() +view_options.file_info = file_info +view_options.view_format = "PDF" +view_options.render_options = pdf_options +view_options.output_path = "output/contract.pdf" + +# Render the document +result = viewer_api.view(view_options) + +# Process the PDF output +print(f"Document rendered to PDF format") +print(f"PDF file path: {result.file}") +print(f"Download URL: {result.file}") + +# Generate example code for PDF viewer embedding +print("\nExample HTML code for embedding the PDF:") +print("html") +print("
") +print("

Contract Document

") +print(" ") +print("

It appears your browser doesn't support embedded PDFs.

") +print(f"

Download the PDF instead.

") +print(" ") +print("
") +print("") +``` + +### Step 5: Working with Attachments + +Some documents may contain attachments that you can access through ViewResult: + +```python +# Tutorial Code Example: Handling document attachments +from groupdocs_viewer_cloud import ViewOptions, HtmlOptions, FileInfo + +# Set up file info for a document with attachments (e.g., an email with attachments) +file_info = FileInfo() +file_info.file_path = "documents/email-with-attachments.eml" + +# Create HTML options +html_options = HtmlOptions() + +# Set up view options +view_options = ViewOptions() +view_options.file_info = file_info +view_options.view_format = "HTML" +view_options.render_options = html_options +view_options.output_path = "output/email_content" + +# Render the document +result = viewer_api.view(view_options) + +# Check for attachments +if result.attachments and len(result.attachments) > 0: + print(f"Document contains {len(result.attachments)} attachments:") + for attachment in result.attachments: + print(f" - {attachment.name}") + + # Generate example code for displaying attachments list + print("\nExample HTML code for displaying attachments:") + print("html") + print("
") + print("

Attachments

") + print(" ") + print("
") + print("") + print("") + print("") +else: + print("Document does not contain attachments") +``` + +### Step 6: Building a Complete Document Viewer with ViewResult + +Now let's combine our knowledge to build a complete viewer interface: + +```python +# Tutorial Code Example: Complete document viewer application +from groupdocs_viewer_cloud import ViewOptions, HtmlOptions, FileInfo +import json + +# Set up file info +file_info = FileInfo() +file_info.file_path = "documents/technical-document.pdf" + +# Create HTML options with external resources +html_options = HtmlOptions() +html_options.external_resources = True +html_options.is_responsive = True + +# Set up view options +view_options = ViewOptions() +view_options.file_info = file_info +view_options.view_format = "HTML" +view_options.render_options = html_options +view_options.output_path = "output/technical_doc_html" + +# Render the document +result = viewer_api.view(view_options) + +# Generate complete viewer application with ViewResult data +print("Complete HTML document viewer application:") +print("html") +print("") +print("") +print("") +print(" ") +print(" ") +print(" Document Viewer - Technical Document") +print(" ") +print("") +print("") +print("
") +print("
") +print(" ") +print("
") +print(" ") +print(" 100%") +print(" ") +print(" ") +print("
") +print("
") +print("
") +print("
") +print("
Loading document...
") +print("
") +print("
") +print("
") +print("") +print(" ") +print("") +print("") +print("") +``` + +## Try It Yourself + +Now that you've learned how to work with ViewResult, try these exercises: + +1. Create a viewer interface that displays multiple pages side by side +2. Implement a thumbnail navigator using the page URLs from ViewResult +3. Build a simple document management system that lists document attachments and allows you to view them + +## Troubleshooting Tips + +- Pages not displaying: Verify that the download URLs are accessible and that you're fetching them correctly +- Resource loading issues: When using external resources, ensure that resource paths are correctly referenced +- Authentication problems: Check if the download URLs require authentication and implement proper headers +- Cross-origin issues: Be aware that loading resources from different domains may require CORS configuration + +## What You've Learned + +In this tutorial, you've mastered: +- How to interpret the ViewResult structure after document rendering +- Accessing page content and resources for different output formats +- Building HTML, image, and PDF viewers using ViewResult data +- Working with document attachments +- Creating complete viewer applications with navigation and zoom controls + +## Next Steps + +Ready to learn about extracting document information? Continue your learning with our [InfoResult Tutorial](/data-structures/info-result) to discover how to extract metadata and page information from documents. + +## Helpful Resources + +- [Product Page](https://products.groupdocs.cloud/viewer/) +- [Documentation](https://docs.groupdocs.cloud/viewer/) +- [API Reference UI](https://reference.groupdocs.cloud/viewer/) +- [Free Support](https://forum.groupdocs.cloud/c/viewer/9) +- [Free Trial](https://dashboard.groupdocs.cloud/#/apps) + +Have questions about working with ViewResult? Post them on our [support forum](https://forum.groupdocs.cloud/c/viewer/9). \ No newline at end of file diff --git a/content/viewer/english/getting-started/_index.md b/content/viewer/english/getting-started/_index.md new file mode 100644 index 0000000..a487835 --- /dev/null +++ b/content/viewer/english/getting-started/_index.md @@ -0,0 +1,48 @@ +--- +title: GroupDocs.Viewer Cloud API Developer Guide Tutorials +description: Step-by-step tutorials for developers to master GroupDocs.Viewer Cloud API capabilities from basic to advanced features +url: /getting-started/ +weight: 10 +--- + +# GroupDocs.Viewer Cloud API Developer Guide Tutorials + +Welcome to our comprehensive tutorial series for the GroupDocs.Viewer Cloud API! These hands-on tutorials are designed to help developers quickly master the powerful document viewing capabilities offered by GroupDocs.Viewer Cloud. + +## Learning Path + +Our tutorials follow a structured learning path that will take you from the basics to advanced implementation techniques: + +1. Getting Started - Learn the fundamentals of GroupDocs.Viewer Cloud API +2. Working with Files - Master file operations for your document viewing scenarios +3. Working with Folders - Understand folder management to organize your documents +4. Working with Storage - Learn storage operations for efficient document management +5. Metered Consumption - Implement and monitor your license consumption + +## Available Tutorials + +### Basic Tutorials + +- [Tutorial: How to Work with Files in GroupDocs.Viewer Cloud](/getting-started/working-with-files/) - Learn essential file operations including downloading, uploading, copying, moving, and deleting files for your document viewing solutions. + +- [Tutorial: Managing Folders in GroupDocs.Viewer Cloud](/getting-started/working-with-folder/) - Master folder operations like creating, listing, copying, moving, and deleting folders to organize your documents efficiently. + +### Intermediate Tutorials + +- [Tutorial: Working with Storage in GroupDocs.Viewer Cloud](/getting-started/working-with-storage/) - Learn how to check storage existence, monitor storage space usage, verify file existence, and manage file versions. + +- [Tutorial: Implementing Metered Consumption for GroupDocs.Viewer Cloud](/getting-started/metered-consumption/) - Learn how to implement and monitor your license consumption with Docker-based deployments. + +## Resources + +To support your learning journey, here are some helpful links: + +- [Product Page](https://products.groupdocs.cloud/viewer/) +- [Documentation](https://docs.groupdocs.cloud/viewer/) +- [Live Demo](https://products.groupdocs.app/viewer/family) +- [API Reference UI](https://reference.groupdocs.cloud/viewer/) +- [Blog](https://blog.groupdocs.cloud/categories/groupdocs.viewer-cloud-product-family/) +- [Free Support](https://forum.groupdocs.cloud/c/viewer/9) +- [Free Trial](https://dashboard.groupdocs.cloud/#/apps) + +We welcome your feedback on these tutorials! If you have questions or suggestions, please reach out through our [support forum](https://forum.groupdocs.cloud/c/viewer/9). diff --git a/content/viewer/english/getting-started/metered-consumption/_index.md b/content/viewer/english/getting-started/metered-consumption/_index.md new file mode 100644 index 0000000..9b56cc8 --- /dev/null +++ b/content/viewer/english/getting-started/metered-consumption/_index.md @@ -0,0 +1,851 @@ +--- +title: Implementing Metered Consumption for GroupDocs.Viewer Cloud Tutorial +url: /getting-started/metered-consumption/ +description: Learn how to implement and monitor metered license consumption in GroupDocs.Viewer Cloud with Docker deployments in this step-by-step tutorial. +weight: 10 +--- + +# Tutorial: Implementing Metered Consumption for GroupDocs.Viewer Cloud + +## Learning Objectives + +In this tutorial, you'll learn how to: +- Set up a Docker version of GroupDocs.Viewer Cloud +- Implement metered license tracking +- Monitor license consumption +- Retrieve consumption metrics +- Analyze usage patterns + +## Prerequisites + +Before you begin this tutorial, you need: +- A GroupDocs Cloud account with metered license +- Docker installed on your system +- Basic understanding of Docker containers +- Familiarity with REST APIs and your preferred programming language +- Development environment with the respective GroupDocs.Viewer Cloud SDK installed + +## Introduction + +Monitoring license consumption is critical for organizations that leverage document processing services. GroupDocs.Viewer Cloud's Docker version provides metered licensing, allowing you to track exact usage and optimize costs. + +In this tutorial, we'll walk through the process of implementing metered consumption tracking in a self-hosted Docker deployment of GroupDocs.Viewer Cloud. We'll create a scenario where you're building an enterprise document portal and need to monitor license consumption for reporting and cost allocation. + +Let's learn how to implement metered consumption tracking using the GroupDocs.Viewer Cloud API. + +## 1. Setting Up Docker Version of GroupDocs.Viewer Cloud + +First, let's understand how to set up a Docker version of GroupDocs.Viewer Cloud, which is necessary for implementing metered consumption. + +### Step-by-Step Instructions + +1. Ensure Docker is installed and running on your system +2. Pull the GroupDocs.Viewer Cloud Docker image from the container registry +3. Configure the container with your metered license +4. Start the container with the proper port mappings +5. Verify the service is running correctly + +### Docker Setup Example + +```bash +# Pull the GroupDocs.Viewer Cloud Docker image +docker pull groupdocs/viewer-cloud + +# Run the container with proper configuration +docker run -d -p 8080:80 -p 8081:443 \ + -e "GROUPDOCS_LIC_PATH=/licenses" \ + -v /local/path/to/licenses:/licenses \ + groupdocs/viewer-cloud +``` + +## 2. Retrieving Metered License Consumption + +Now, let's learn how to retrieve metered license consumption data from your GroupDocs.Viewer Cloud Docker deployment. + +### Step-by-Step Instructions + +1. Authenticate with the GroupDocs.Viewer Cloud API +2. Create a request to the consumption endpoint +3. Execute the request to retrieve consumption data +4. Process and analyze the consumption information + +### cURL Example + +```bash +curl -v "http://localhost:8080/v2.0/viewer/consumption" \ + -X GET \ + -H "Accept: application/json" \ + -H "Authorization: Bearer YOUR_JWT_TOKEN" +``` + +### SDK Examples + +Let's see how to retrieve metered consumption using various SDKs: + +#### C# Example + +```csharp +using GroupDocs.Viewer.Cloud.Sdk.Api; +using GroupDocs.Viewer.Cloud.Sdk.Client; +using System; + +namespace GroupDocs.Viewer.Cloud.Examples +{ + class GetMeteredConsumptionExample + { + public static void Run() + { + // Authenticate with the API + var configuration = new Configuration(Common.MyAppSid, Common.MyAppKey); + + // The base URL should point to your Docker deployment + configuration.ApiBaseUrl = "http://localhost:8080/v2.0"; + + var apiInstance = new LicenseApi(configuration); + + try + { + // Execute the request to get consumption data + var response = apiInstance.GetConsumptionCredit(); + + // Process the consumption information + Console.WriteLine($"Credits consumed: {response.Credit}"); + Console.WriteLine($"Megabytes processed: {response.Quantity}"); + + // Calculate average MB per credit + if (response.Credit > 0) + { + double mbPerCredit = response.Quantity / response.Credit; + Console.WriteLine($"Average MB per credit: {mbPerCredit:F2}"); + } + } + catch (Exception e) + { + Console.WriteLine("Error retrieving consumption data: " + e.Message); + } + } + } +} +``` + +#### Java Example + +```java +package examples; + +import com.groupdocs.cloud.viewer.api.*; +import com.groupdocs.cloud.viewer.client.ApiException; +import com.groupdocs.cloud.viewer.client.Configuration; +import com.groupdocs.cloud.viewer.model.*; + +public class GetMeteredConsumptionExample { + + public static void main(String[] args) { + // Authenticate with the API + String clientId = "YOUR_CLIENT_ID"; + String clientSecret = "YOUR_CLIENT_SECRET"; + + // Create configuration with Docker deployment URL + Configuration configuration = new Configuration(clientId, clientSecret); + configuration.setApiBaseUrl("http://localhost:8080/v2.0"); + + // Create API instance + LicenseApi apiInstance = new LicenseApi(configuration); + + try { + // Execute the request to get consumption data + ConsumptionResult response = apiInstance.getConsumptionCredit(); + + // Process the consumption information + System.out.println("Credits consumed: " + response.getCredit()); + System.out.println("Megabytes processed: " + response.getQuantity()); + + // Calculate average MB per credit + if (response.getCredit() > 0) { + double mbPerCredit = response.getQuantity() / response.getCredit(); + System.out.printf("Average MB per credit: %.2f%n", mbPerCredit); + } + } catch (ApiException e) { + System.err.println("Error retrieving consumption data: " + e.getMessage()); + e.printStackTrace(); + } + } +} +``` + +#### Python Example + +```python +import groupdocs_viewer_cloud +from groupdocs_viewer_cloud import Configuration + +# Authenticate with the API +app_sid = "YOUR_CLIENT_ID" +app_key = "YOUR_CLIENT_SECRET" + +# Create configuration with Docker deployment URL +configuration = groupdocs_viewer_cloud.Configuration(app_sid, app_key) +configuration.api_base_url = "http://localhost:8080/v2.0" + +# Create API instance +api_instance = groupdocs_viewer_cloud.LicenseApi(configuration) + +try: + # Execute the request to get consumption data + response = api_instance.get_consumption_credit() + + # Process the consumption information + print(f"Credits consumed: {response.credit}") + print(f"Megabytes processed: {response.quantity}") + + # Calculate average MB per credit + if response.credit > 0: + mb_per_credit = response.quantity / response.credit + print(f"Average MB per credit: {mb_per_credit:.2f}") + +except groupdocs_viewer_cloud.ApiException as e: + print(f"Error retrieving consumption data: {e.message}") +``` + +### Try It Yourself + +1. Replace the base URL with your Docker deployment's address +2. Replace the authentication credentials with your actual values +3. Run the code and verify that the consumption data is retrieved +4. Analyze the credit consumption and megabytes processed + +## 3. Monitoring Consumption Over Time + +Let's learn how to implement a solution for tracking consumption over time to identify trends and optimize usage. + +### Step-by-Step Instructions + +1. Create a scheduled task to collect consumption data periodically +2. Store historical consumption data in a database +3. Implement analytics to track usage patterns +4. Create dashboards or reports to visualize consumption trends + +### Implementation Example (C#) + +```csharp +using GroupDocs.Viewer.Cloud.Sdk.Api; +using GroupDocs.Viewer.Cloud.Sdk.Client; +using System; +using System.Threading.Tasks; +using System.Collections.Generic; +using System.Data.SQLite; +using System.Threading; + +namespace GroupDocs.Viewer.Cloud.Examples +{ + class ConsumptionMonitoringService + { + private readonly Configuration configuration; + private readonly string dbPath; + private Timer timer; + + public ConsumptionMonitoringService(string clientId, string clientSecret, string apiBaseUrl, string dbPath) + { + // Initialize configuration + configuration = new Configuration(clientId, clientSecret) + { + ApiBaseUrl = apiBaseUrl + }; + + this.dbPath = dbPath; + + // Create database if not exists + CreateDatabaseIfNotExists(); + } + + public void StartMonitoring(TimeSpan interval) + { + // Start timer to collect data at specified interval + timer = new Timer(async _ => await CollectConsumptionData(), null, TimeSpan.Zero, interval); + + Console.WriteLine($"Monitoring started with interval: {interval}"); + } + + public void StopMonitoring() + { + timer?.Dispose(); + Console.WriteLine("Monitoring stopped"); + } + + private async Task CollectConsumptionData() + { + try + { + var apiInstance = new LicenseApi(configuration); + var response = apiInstance.GetConsumptionCredit(); + + // Store data in database + StoreConsumptionData(response.Credit, response.Quantity); + + Console.WriteLine($"[{DateTime.Now}] Data collected - Credits: {response.Credit}, MB: {response.Quantity}"); + } + catch (Exception ex) + { + Console.WriteLine($"Error collecting consumption data: {ex.Message}"); + } + } + + private void CreateDatabaseIfNotExists() + { + try + { + // Create SQLite database if not exists + SQLiteConnection.CreateFile(dbPath); + + using (var connection = new SQLiteConnection($"Data Source={dbPath};Version=3;")) + { + connection.Open(); + + // Create table for consumption data + string sql = @" + CREATE TABLE IF NOT EXISTS consumption_history ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + timestamp DATETIME NOT NULL, + credits REAL NOT NULL, + megabytes REAL NOT NULL + )"; + + using (var command = new SQLiteCommand(sql, connection)) + { + command.ExecuteNonQuery(); + } + } + + Console.WriteLine("Database initialized successfully"); + } + catch (Exception ex) + { + Console.WriteLine($"Error creating database: {ex.Message}"); + } + } + + private void StoreConsumptionData(decimal credits, decimal megabytes) + { + try + { + using (var connection = new SQLiteConnection($"Data Source={dbPath};Version=3;")) + { + connection.Open(); + + string sql = @" + INSERT INTO consumption_history (timestamp, credits, megabytes) + VALUES (@timestamp, @credits, @megabytes)"; + + using (var command = new SQLiteCommand(sql, connection)) + { + command.Parameters.AddWithValue("@timestamp", DateTime.Now); + command.Parameters.AddWithValue("@credits", (double)credits); + command.Parameters.AddWithValue("@megabytes", (double)megabytes); + command.ExecuteNonQuery(); + } + } + } + catch (Exception ex) + { + Console.WriteLine($"Error storing consumption data: {ex.Message}"); + } + } + + public List GetConsumptionHistory(DateTime startDate, DateTime endDate) + { + var records = new List(); + + try + { + using (var connection = new SQLiteConnection($"Data Source={dbPath};Version=3;")) + { + connection.Open(); + + string sql = @" + SELECT timestamp, credits, megabytes + FROM consumption_history + WHERE timestamp BETWEEN @startDate AND @endDate + ORDER BY timestamp"; + + using (var command = new SQLiteCommand(sql, connection)) + { + command.Parameters.AddWithValue("@startDate", startDate); + command.Parameters.AddWithValue("@endDate", endDate); + + using (var reader = command.ExecuteReader()) + { + while (reader.Read()) + { + records.Add(new ConsumptionRecord + { + Timestamp = Convert.ToDateTime(reader["timestamp"]), + Credits = Convert.ToDecimal(reader["credits"]), + Megabytes = Convert.ToDecimal(reader["megabytes"]) + }); + } + } + } + } + } + catch (Exception ex) + { + Console.WriteLine($"Error retrieving consumption history: {ex.Message}"); + } + + return records; + } + } + + class ConsumptionRecord + { + public DateTime Timestamp { get; set; } + public decimal Credits { get; set; } + public decimal Megabytes { get; set; } + } +} +``` + +### Example Usage + +```csharp +class Program +{ + static void Main(string[] args) + { + // Initialize the monitoring service + var service = new ConsumptionMonitoringService( + "YOUR_CLIENT_ID", + "YOUR_CLIENT_SECRET", + "http://localhost:8080/v2.0", + "consumption_data.db" + ); + + // Start monitoring with 1-hour interval + service.StartMonitoring(TimeSpan.FromHours(1)); + + Console.WriteLine("Press any key to stop monitoring..."); + Console.ReadKey(); + + // Stop monitoring + service.StopMonitoring(); + + // Generate report for the last 7 days + var endDate = DateTime.Now; + var startDate = endDate.AddDays(-7); + + var history = service.GetConsumptionHistory(startDate, endDate); + + Console.WriteLine($"\nConsumption Report ({startDate} to {endDate}):"); + Console.WriteLine("Timestamp\t\tCredits\t\tMegabytes"); + Console.WriteLine("--------------------------------------------------"); + + foreach (var record in history) + { + Console.WriteLine($"{record.Timestamp}\t{record.Credits}\t\t{record.Megabytes}"); + } + + // Calculate total consumption + var totalCredits = history.Sum(r => r.Credits); + var totalMegabytes = history.Sum(r => r.Megabytes); + + Console.WriteLine("--------------------------------------------------"); + Console.WriteLine($"Total:\t\t\t{totalCredits}\t\t{totalMegabytes}"); + } +} +``` + +### Try It Yourself + +1. Implement the monitoring service in your preferred language +2. Schedule the monitoring to run at appropriate intervals for your needs +3. Create a simple dashboard to visualize consumption trends +4. Use the historical data to predict future consumption and costs + +## 4. Optimizing Consumption and Cost + +Let's explore strategies for optimizing your metered license consumption to minimize costs while maximizing the value of GroupDocs.Viewer Cloud. + +### Optimization Strategies + +#### 1. Document Caching + +Implement caching for rendered documents to avoid reprocessing the same documents multiple times. + +```csharp +public class DocumentCache +{ + private readonly Dictionary cache = new Dictionary(); + private readonly int maxCacheSize; + + public DocumentCache(int maxCacheSize = 100) + { + this.maxCacheSize = maxCacheSize; + } + + public bool TryGetDocument(string documentId, out byte[] documentData) + { + return cache.TryGetValue(documentId, out documentData); + } + + public void CacheDocument(string documentId, byte[] documentData) + { + // Implement cache eviction if size exceeds maximum + if (cache.Count >= maxCacheSize) + { + // Simple LRU implementation: remove first item + var firstKey = cache.Keys.First(); + cache.Remove(firstKey); + } + + cache[documentId] = documentData; + } +} +``` + +#### 2. Batch Processing + +Process documents in batches to optimize API usage and reduce overhead. + +```csharp +public class BatchProcessor +{ + private readonly List queue = new List(); + private readonly int batchSize; + private readonly Timer timer; + + public BatchProcessor(int batchSize = 10, int processingIntervalSeconds = 60) + { + this.batchSize = batchSize; + timer = new Timer(_ => ProcessBatch(), null, + TimeSpan.FromSeconds(processingIntervalSeconds), + TimeSpan.FromSeconds(processingIntervalSeconds)); + } + + public void QueueDocument(string documentId, Action callback) + { + lock (queue) + { + queue.Add(new DocumentTask { DocumentId = documentId, Callback = callback }); + } + } + + private void ProcessBatch() + { + List batchToProcess; + + lock (queue) + { + batchToProcess = queue.Take(batchSize).ToList(); + queue.RemoveRange(0, Math.Min(batchSize, queue.Count)); + } + + if (batchToProcess.Count == 0) + return; + + Console.WriteLine($"Processing batch of {batchToProcess.Count} documents"); + + // Here you would implement actual batch processing + // ... + + // Simulating processing and calling callbacks + foreach (var task in batchToProcess) + { + // Simulate document data + var documentData = new byte[1024]; + task.Callback(documentData); + } + } + + private class DocumentTask + { + public string DocumentId { get; set; } + public Action Callback { get; set; } + } +} +``` + +#### 3. Document Compression + +Implement compression for document storage to reduce the data transfer volume. + +```csharp +public static class DocumentCompressor +{ + public static byte[] Compress(byte[] data) + { + using (var compressedStream = new MemoryStream()) + using (var gzipStream = new GZipStream(compressedStream, CompressionLevel.Optimal)) + { + gzipStream.Write(data, 0, data.Length); + gzipStream.Close(); + return compressedStream.ToArray(); + } + } + + public static byte[] Decompress(byte[] compressedData) + { + using (var compressedStream = new MemoryStream(compressedData)) + using (var gzipStream = new GZipStream(compressedStream, CompressionMode.Decompress)) + using (var resultStream = new MemoryStream()) + { + gzipStream.CopyTo(resultStream); + return resultStream.ToArray(); + } + } +} +``` + +### Try These Optimization Techniques + +1. Implement document caching to avoid reprocessing the same documents +2. Use batch processing for bulk document operations +3. Apply compression techniques to reduce data transfer volume +4. Track consumption metrics before and after implementing optimizations + +## 5. Implementing Consumption Alerting + +Let's create a system for alerting when consumption reaches certain thresholds, helping you proactively manage license usage. + +### Alert Implementation Example + +```csharp +public class ConsumptionAlertService +{ + private readonly Configuration configuration; + private readonly decimal warningThreshold; + private readonly decimal criticalThreshold; + private readonly List> alertHandlers = new List>(); + + public ConsumptionAlertService( + string clientId, + string clientSecret, + string apiBaseUrl, + decimal warningThreshold = 70, + decimal criticalThreshold = 90) + { + // Initialize configuration + configuration = new Configuration(clientId, clientSecret) + { + ApiBaseUrl = apiBaseUrl + }; + + this.warningThreshold = warningThreshold; + this.criticalThreshold = criticalThreshold; + } + + public void RegisterAlertHandler(Action handler) + { + alertHandlers.Add(handler); + } + + public void CheckConsumption(decimal monthlyLimitCredits) + { + try + { + var apiInstance = new LicenseApi(configuration); + var consumption = apiInstance.GetConsumptionCredit(); + + // Calculate percentage of monthly limit + decimal percentUsed = (consumption.Credit / monthlyLimitCredits) * 100; + + // Determine alert level + AlertLevel level = AlertLevel.Normal; + + if (percentUsed >= criticalThreshold) + level = AlertLevel.Critical; + else if (percentUsed >= warningThreshold) + level = AlertLevel.Warning; + + // Create alert if not normal + if (level != AlertLevel.Normal) + { + var alert = new ConsumptionAlert + { + Timestamp = DateTime.Now, + Level = level, + CreditsUsed = consumption.Credit, + MonthlyLimit = monthlyLimitCredits, + PercentUsed = percentUsed, + Message = $"License consumption is at {percentUsed:F1}% of monthly limit ({consumption.Credit} of {monthlyLimitCredits} credits used)" + }; + + // Notify all handlers + foreach (var handler in alertHandlers) + { + handler(alert); + } + } + } + catch (Exception ex) + { + Console.WriteLine($"Error checking consumption for alerts: {ex.Message}"); + } + } + + public enum AlertLevel + { + Normal, + Warning, + Critical + } + + public class ConsumptionAlert + { + public DateTime Timestamp { get; set; } + public AlertLevel Level { get; set; } + public decimal CreditsUsed { get; set; } + public decimal MonthlyLimit { get; set; } + public decimal PercentUsed { get; set; } + public string Message { get; set; } + } +} +``` + +### Alert Handler Examples + +```csharp +// Email Alert Handler +static void EmailAlertHandler(ConsumptionAlertService.ConsumptionAlert alert) +{ + Console.WriteLine($"Sending email alert: {alert.Level} - {alert.Message}"); + + // Implement your email sending logic here + // Example using System.Net.Mail: + /* + using (var client = new SmtpClient("smtp.example.com")) + { + client.Credentials = new NetworkCredential("username", "password"); + var message = new MailMessage( + "alerts@yourcompany.com", + "admin@yourcompany.com", + $"GroupDocs Viewer {alert.Level} Alert", + alert.Message + ); + client.Send(message); + } + */ +} + +// Slack Alert Handler +static void SlackAlertHandler(ConsumptionAlertService.ConsumptionAlert alert) +{ + Console.WriteLine($"Sending Slack alert: {alert.Level} - {alert.Message}"); + + // Implement your Slack webhook integration here + // Example using HttpClient: + /* + using (var client = new HttpClient()) + { + var payload = new + { + text = $"*{alert.Level} Alert*: {alert.Message}", + channel = "#alerts", + username = "GroupDocs Monitor" + }; + + var content = new StringContent(JsonConvert.SerializeObject(payload), Encoding.UTF8, "application/json"); + client.PostAsync("https://hooks.slack.com/services/YOUR_WEBHOOK_URL", content).Wait(); + } + */ +} + +// Log Alert Handler +static void LogAlertHandler(ConsumptionAlertService.ConsumptionAlert alert) +{ + string logMessage = $"[{alert.Timestamp}] {alert.Level}: {alert.Message}"; + Console.WriteLine(logMessage); + + // Append to log file + File.AppendAllText("consumption_alerts.log", logMessage + Environment.NewLine); +} +``` + +### Example Usage + +```csharp +class Program +{ + static void Main(string[] args) + { + // Initialize the alert service + var alertService = new ConsumptionAlertService( + "YOUR_CLIENT_ID", + "YOUR_CLIENT_SECRET", + "http://localhost:8080/v2.0", + warningThreshold: 70, // Alert at 70% usage + criticalThreshold: 90 // Critical alert at 90% usage + ); + + // Register alert handlers + alertService.RegisterAlertHandler(EmailAlertHandler); + alertService.RegisterAlertHandler(SlackAlertHandler); + alertService.RegisterAlertHandler(LogAlertHandler); + + // Check consumption with a monthly limit of 10,000 credits + alertService.CheckConsumption(10000); + + // In production, you'd typically set this up as a scheduled task + // that runs daily or hourly + } + + // Alert handlers defined here... +} +``` + +### Try It Yourself + +1. Implement the alert service with appropriate thresholds for your needs +2. Configure alert handlers for your organization's communication channels +3. Set up scheduled tasks to check consumption regularly +4. Test the alerts by temporarily lowering the thresholds + +## Common Issues and Troubleshooting + +When working with metered consumption, you might encounter these common issues: + +1. Docker Connectivity Issues + - Problem: Unable to connect to Docker deployment + - Solution: Verify Docker container is running; check network settings and port mapping + +2. Authentication Errors + - Problem: API returns 401 Unauthorized + - Solution: Check your Client ID and Client Secret; ensure JWT token is valid + +3. Consumption Data Not Available + - Problem: API returns error when retrieving consumption data + - Solution: Verify metered license is properly configured in Docker container + +4. Inaccurate Consumption Reporting + - Problem: Consumption data doesn't match expected usage + - Solution: Check for caching or CDN usage that might be affecting actual API calls + +## What You've Learned + +In this tutorial, you've learned how to: +- Set up a Docker version of GroupDocs.Viewer Cloud +- Implement metered license tracking +- Monitor license consumption over time +- Optimize consumption to reduce costs +- Set up alerts for proactive consumption management + +You now have the essential skills to implement a comprehensive metered consumption monitoring system for your GroupDocs.Viewer Cloud deployment. + +## Further Practice + +To reinforce your learning, try these exercises: +1. Create a detailed consumption dashboard with historical trends +2. Implement cost allocation by user or department +3. Develop usage forecasting based on historical patterns +4. Implement automatic scaling of resources based on consumption patterns + +## Resources + +- [Product Page](https://products.groupdocs.cloud/viewer/) +- [Documentation](https://docs.groupdocs.cloud/viewer/) +- [Live Demo](https://products.groupdocs.app/viewer/family) +- [API Reference UI](https://reference.groupdocs.cloud/viewer/) +- [Blog](https://blog.groupdocs.cloud/categories/groupdocs.viewer-cloud-product-family/) +- [Free Support](https://forum.groupdocs.cloud/c/viewer/9) +- [Free Trial](https://dashboard.groupdocs.cloud/#/apps) + +Have questions about this tutorial? Feel free to reach out on our [support forum](https://forum.groupdocs.cloud/c/viewer/9). \ No newline at end of file diff --git a/content/viewer/english/getting-started/working-with-files/_index.md b/content/viewer/english/getting-started/working-with-files/_index.md new file mode 100644 index 0000000..727d07d --- /dev/null +++ b/content/viewer/english/getting-started/working-with-files/_index.md @@ -0,0 +1,771 @@ +--- +title: How to Work with Files in GroupDocs.Viewer Cloud Tutorial +url: /getting-started/working-with-files/ +description: Learn how to manage files in GroupDocs.Viewer Cloud with this step-by-step tutorial covering downloading, uploading, copying, moving, and deleting files. +weight: 20 +--- + +# Tutorial: How to Work with Files in GroupDocs.Viewer Cloud + +## Learning Objectives + +In this tutorial, you'll learn how to: +- Download files from GroupDocs Cloud Storage +- Upload files to GroupDocs Cloud Storage +- Delete files from GroupDocs Cloud Storage +- Copy files within GroupDocs Cloud Storage +- Move files within GroupDocs Cloud Storage + +## Prerequisites + +Before you begin this tutorial, you need: +- A GroupDocs Cloud account (if you don't have one, [sign up for a free trial](https://dashboard.groupdocs.cloud/#/apps)) +- Client ID and Client Secret credentials +- Basic understanding of REST APIs and your preferred programming language +- Development environment with the respective GroupDocs.Viewer Cloud SDK installed + +## Introduction + +Managing files is a fundamental requirement when working with document viewing solutions. GroupDocs.Viewer Cloud provides comprehensive APIs to handle all aspects of file management. In this tutorial, we'll explore how to perform essential file operations. + +Let's start with a real-world scenario: You're developing a document management system that needs to fetch documents from the cloud, display them to users, and allow for file operations like uploading new versions or organizing documents. + +## 1. Download Files from Cloud Storage + +The first operation we'll learn is downloading files. This is essential when you need to retrieve documents from your cloud storage. + +### Step-by-Step Instructions + +1. Authenticate with the GroupDocs.Viewer Cloud API +2. Specify the file path of the document you want to download +3. Optionally specify the storage name (if you're not using the default storage) +4. Execute the download request +5. Process the downloaded file + +### cURL Example + +```bash +curl -X GET "https://api.groupdocs.cloud/v2.0/viewer/storage/file/one-page.docx?storageName=MyStorage" \ + -H "accept: multipart/form-data" \ + -H "authorization: Bearer YOUR_ACCESS_TOKEN" +``` + +### SDK Examples + +Let's see how to implement this using various SDKs: + +#### C# Example + +```csharp +using GroupDocs.Viewer.Cloud.Sdk.Api; +using GroupDocs.Viewer.Cloud.Sdk.Client; +using GroupDocs.Viewer.Cloud.Sdk.Model.Requests; +using System; + +namespace GroupDocs.Viewer.Cloud.Examples +{ + class DownloadFileExample + { + public static void Run() + { + // Authenticate with the API + var configuration = new Configuration(Common.MyAppSid, Common.MyAppKey); + var apiInstance = new FileApi(configuration); + + try + { + // Create request with file path and storage name + var request = new DownloadFileRequest("viewerdocs/one-page.docx", Common.MyStorage); + + // Execute the request + var response = apiInstance.DownloadFile(request); + Console.WriteLine("File downloaded successfully, size: " + response.Length); + + // Now you can process the downloaded file, e.g., save it locally + // System.IO.File.WriteAllBytes("local-path/one-page.docx", response); + } + catch (Exception e) + { + Console.WriteLine("Error downloading file: " + e.Message); + } + } + } +} +``` + +#### Java Example + +```java +package examples; + +import com.groupdocs.cloud.viewer.api.*; +import com.groupdocs.cloud.viewer.client.ApiException; +import com.groupdocs.cloud.viewer.model.requests.*; +import java.io.File; +import java.io.FileOutputStream; +import java.io.OutputStream; + +public class DownloadFileExample { + + public static void main(String[] args) { + // Authenticate with the API + FileApi apiInstance = new FileApi(Common.AppSID, Common.AppKey); + + try { + // Create request with file path and storage name + DownloadFileRequest request = new DownloadFileRequest( + "viewerdocs/one-page.docx", // File path + Common.MyStorage, // Storage name + null // Version ID (optional) + ); + + // Execute the request + File response = apiInstance.downloadFile(request); + System.out.println("File downloaded successfully, size: " + response.length()); + + // Optional: Save to local path + // try (OutputStream os = new FileOutputStream("local-path/one-page.docx")) { + // // Process the file as needed + // } + } catch (ApiException e) { + System.err.println("Error downloading file: " + e.getMessage()); + e.printStackTrace(); + } + } +} +``` + +#### Python Example + +```python +import groupdocs_viewer_cloud +from groupdocs_viewer_cloud import DownloadFileRequest + +# Authenticate with the API +configuration = groupdocs_viewer_cloud.Configuration(Common.app_sid, Common.app_key) +api_instance = groupdocs_viewer_cloud.FileApi(configuration) + +try: + # Create request with file path and storage name + request = DownloadFileRequest("viewerdocs/one-page.docx", Common.my_storage) + + # Execute the request + response = api_instance.download_file(request) + + print(f"File downloaded successfully, size: {len(response)}") + + # Optional: Save to local path + # with open("local-path/one-page.docx", "wb") as f: + # f.write(response) + +except groupdocs_viewer_cloud.ApiException as e: + print(f"Error downloading file: {e.message}") +``` + +### Try It Yourself + +1. Replace `YOUR_APP_SID` and `YOUR_APP_KEY` with your actual application credentials +2. Replace the file path with a document in your storage +3. Run the code and verify that the file downloads successfully +4. Check the response size to make sure it matches your file size + +## 2. Upload Files to Cloud Storage + +Now let's learn how to upload files to your cloud storage, which is necessary when adding new documents to your system. + +### Step-by-Step Instructions + +1. Authenticate with the GroupDocs.Viewer Cloud API +2. Prepare the file you want to upload +3. Specify the destination path in cloud storage +4. Optionally specify the storage name +5. Execute the upload request +6. Verify the upload was successful + +### cURL Example + +```bash +curl -X POST "https://api.groupdocs.cloud/v2.0/viewer/storage/file/viewerdocs/sample-document.docx?storageName=MyStorage" \ + -H "accept: application/json" \ + -H "authorization: Bearer YOUR_ACCESS_TOKEN" \ + -H "Content-Type: multipart/form-data" \ + -F "fileContent=@/local-path/sample-document.docx" +``` + +### SDK Examples + +Let's see how to implement file uploads using various SDKs: + +#### C# Example + +```csharp +using GroupDocs.Viewer.Cloud.Sdk.Api; +using GroupDocs.Viewer.Cloud.Sdk.Client; +using GroupDocs.Viewer.Cloud.Sdk.Model.Requests; +using System; +using System.IO; + +namespace GroupDocs.Viewer.Cloud.Examples +{ + class UploadFileExample + { + public static void Run() + { + // Authenticate with the API + var configuration = new Configuration(Common.MyAppSid, Common.MyAppKey); + var apiInstance = new FileApi(configuration); + + try + { + // Prepare the file stream for upload + var fileStream = File.Open("local-path/sample-document.docx", FileMode.Open); + + // Create upload request + var request = new UploadFileRequest( + "viewerdocs/sample-document.docx", // Destination file path + fileStream, // File content + Common.MyStorage // Storage name + ); + + // Execute the request + var response = apiInstance.UploadFile(request); + Console.WriteLine("File uploaded successfully. Files uploaded: " + response.Uploaded.Count); + } + catch (Exception e) + { + Console.WriteLine("Error uploading file: " + e.Message); + } + } + } +} +``` + +#### Java Example + +```java +package examples; + +import com.groupdocs.cloud.viewer.api.*; +import com.groupdocs.cloud.viewer.client.ApiException; +import com.groupdocs.cloud.viewer.model.*; +import com.groupdocs.cloud.viewer.model.requests.*; +import java.io.File; +import java.nio.file.Paths; + +public class UploadFileExample { + + public static void main(String[] args) { + // Authenticate with the API + FileApi apiInstance = new FileApi(Common.AppSID, Common.AppKey); + + try { + // Prepare the file for upload + File fileToUpload = new File(Paths.get("local-path/sample-document.docx").toString()); + + // Create upload request + UploadFileRequest request = new UploadFileRequest( + "viewerdocs/sample-document.docx", // Destination path + fileToUpload, // File content + Common.MyStorage // Storage name + ); + + // Execute the request + FilesUploadResult response = apiInstance.uploadFile(request); + System.out.println("File uploaded successfully. Files uploaded: " + response.getUploaded().size()); + } catch (ApiException e) { + System.err.println("Error uploading file: " + e.getMessage()); + e.printStackTrace(); + } + } +} +``` + +#### Python Example + +```python +import groupdocs_viewer_cloud +from groupdocs_viewer_cloud import UploadFileRequest + +# Authenticate with the API +configuration = groupdocs_viewer_cloud.Configuration(Common.app_sid, Common.app_key) +api_instance = groupdocs_viewer_cloud.FileApi(configuration) + +try: + # Prepare file path for upload + local_file_path = "local-path/sample-document.docx" + + # Create upload request + request = groupdocs_viewer_cloud.UploadFileRequest( + "viewerdocs/sample-document.docx", # Destination path + local_file_path, # Local file path + Common.my_storage # Storage name + ) + + # Execute the request + response = api_instance.upload_file(request) + + print(f"File uploaded successfully. Files uploaded: {len(response.uploaded)}") + +except groupdocs_viewer_cloud.ApiException as e: + print(f"Error uploading file: {e.message}") +``` + +### Try It Yourself + +1. Replace the file path with your local document path +2. Replace the destination path with your preferred path in cloud storage +3. Run the code and verify that the upload was successful +4. Check your cloud storage dashboard to confirm the file appears + +## 3. Delete Files from Cloud Storage + +Next, let's learn how to delete files from your cloud storage, which is necessary for managing document lifecycles. + +### Step-by-Step Instructions + +1. Authenticate with the GroupDocs.Viewer Cloud API +2. Specify the path of the file you want to delete +3. Optionally specify the storage name +4. Execute the delete request +5. Verify the file was successfully deleted + +### cURL Example + +```bash +curl -X DELETE "https://api.groupdocs.cloud/v2.0/viewer/storage/file/viewerdocs/sample-document.docx?storageName=MyStorage" \ + -H "accept: application/json" \ + -H "authorization: Bearer YOUR_ACCESS_TOKEN" +``` + +### SDK Examples + +Let's implement file deletion using various SDKs: + +#### C# Example + +```csharp +using GroupDocs.Viewer.Cloud.Sdk.Api; +using GroupDocs.Viewer.Cloud.Sdk.Client; +using GroupDocs.Viewer.Cloud.Sdk.Model.Requests; +using System; + +namespace GroupDocs.Viewer.Cloud.Examples +{ + class DeleteFileExample + { + public static void Run() + { + // Authenticate with the API + var configuration = new Configuration(Common.MyAppSid, Common.MyAppKey); + var apiInstance = new FileApi(configuration); + + try + { + // Create delete request + var request = new DeleteFileRequest( + "viewerdocs/sample-document.docx", // File path + Common.MyStorage // Storage name + ); + + // Execute the request + apiInstance.DeleteFile(request); + Console.WriteLine("File deleted successfully."); + } + catch (Exception e) + { + Console.WriteLine("Error deleting file: " + e.Message); + } + } + } +} +``` + +#### Java Example + +```java +package examples; + +import com.groupdocs.cloud.viewer.api.*; +import com.groupdocs.cloud.viewer.client.ApiException; +import com.groupdocs.cloud.viewer.model.requests.*; + +public class DeleteFileExample { + + public static void main(String[] args) { + // Authenticate with the API + FileApi apiInstance = new FileApi(Common.AppSID, Common.AppKey); + + try { + // Create delete request + DeleteFileRequest request = new DeleteFileRequest( + "viewerdocs/sample-document.docx", // File path + Common.MyStorage, // Storage name + null // Version ID (optional) + ); + + // Execute the request + apiInstance.deleteFile(request); + System.out.println("File deleted successfully."); + } catch (ApiException e) { + System.err.println("Error deleting file: " + e.getMessage()); + e.printStackTrace(); + } + } +} +``` + +#### Python Example + +```python +import groupdocs_viewer_cloud +from groupdocs_viewer_cloud import DeleteFileRequest + +# Authenticate with the API +configuration = groupdocs_viewer_cloud.Configuration(Common.app_sid, Common.app_key) +api_instance = groupdocs_viewer_cloud.FileApi(configuration) + +try: + # Create delete request + request = DeleteFileRequest( + "viewerdocs/sample-document.docx", # File path + Common.my_storage # Storage name + ) + + # Execute the request + api_instance.delete_file(request) + + print("File deleted successfully.") + +except groupdocs_viewer_cloud.ApiException as e: + print(f"Error deleting file: {e.message}") +``` + +### Try It Yourself + +1. Replace the file path with a document in your storage that you wish to delete +2. Run the code and verify that the deletion was successful +3. Check your cloud storage dashboard to confirm the file no longer appears + +## 4. Copy Files within Cloud Storage + +Let's explore how to copy files within your cloud storage, which is useful when you need to duplicate documents. + +### Step-by-Step Instructions + +1. Authenticate with the GroupDocs.Viewer Cloud API +2. Specify the source file path +3. Specify the destination file path +4. Optionally specify the source and destination storage names +5. Execute the copy request +6. Verify the file was successfully copied + +### cURL Example + +```bash +curl -X PUT "https://api.groupdocs.cloud/v2.0/viewer/storage/file/copy/viewerdocs/source-document.docx?destPath=viewerdocs/destination-document.docx&srcStorageName=MyStorage&destStorageName=MyStorage" \ + -H "accept: application/json" \ + -H "authorization: Bearer YOUR_ACCESS_TOKEN" +``` + +### SDK Examples + +Let's implement file copying using various SDKs: + +#### C# Example + +```csharp +using GroupDocs.Viewer.Cloud.Sdk.Api; +using GroupDocs.Viewer.Cloud.Sdk.Client; +using GroupDocs.Viewer.Cloud.Sdk.Model.Requests; +using System; + +namespace GroupDocs.Viewer.Cloud.Examples +{ + class CopyFileExample + { + public static void Run() + { + // Authenticate with the API + var configuration = new Configuration(Common.MyAppSid, Common.MyAppKey); + var apiInstance = new FileApi(configuration); + + try + { + // Create copy request + var request = new CopyFileRequest( + "viewerdocs/source-document.docx", // Source file path + "viewerdocs/destination-document.docx", // Destination file path + Common.MyStorage, // Source storage name + Common.MyStorage // Destination storage name + ); + + // Execute the request + apiInstance.CopyFile(request); + Console.WriteLine("File copied successfully."); + } + catch (Exception e) + { + Console.WriteLine("Error copying file: " + e.Message); + } + } + } +} +``` + +#### Java Example + +```java +package examples; + +import com.groupdocs.cloud.viewer.api.*; +import com.groupdocs.cloud.viewer.client.ApiException; +import com.groupdocs.cloud.viewer.model.requests.*; + +public class CopyFileExample { + + public static void main(String[] args) { + // Authenticate with the API + FileApi apiInstance = new FileApi(Common.AppSID, Common.AppKey); + + try { + // Create copy request + CopyFileRequest request = new CopyFileRequest( + "viewerdocs/source-document.docx", // Source file path + "viewerdocs/destination-document.docx", // Destination file path + Common.MyStorage, // Source storage name + Common.MyStorage, // Destination storage name + null // Version ID (optional) + ); + + // Execute the request + apiInstance.copyFile(request); + System.out.println("File copied successfully."); + } catch (ApiException e) { + System.err.println("Error copying file: " + e.getMessage()); + e.printStackTrace(); + } + } +} +``` + +#### Python Example + +```python +import groupdocs_viewer_cloud +from groupdocs_viewer_cloud import CopyFileRequest + +# Authenticate with the API +configuration = groupdocs_viewer_cloud.Configuration(Common.app_sid, Common.app_key) +api_instance = groupdocs_viewer_cloud.FileApi(configuration) + +try: + # Create copy request + request = CopyFileRequest( + "viewerdocs/source-document.docx", # Source file path + "viewerdocs/destination-document.docx", # Destination file path + Common.my_storage, # Source storage name + Common.my_storage # Destination storage name + ) + + # Execute the request + api_instance.copy_file(request) + + print("File copied successfully.") + +except groupdocs_viewer_cloud.ApiException as e: + print(f"Error copying file: {e.message}") +``` + +### Try It Yourself + +1. Replace the source file path with a document in your storage +2. Replace the destination file path with your preferred path +3. Run the code and verify that the copy was successful +4. Check your cloud storage dashboard to confirm both files appear + +## 5. Move Files within Cloud Storage + +Finally, let's learn how to move files within your cloud storage, which is useful for organizing your documents. + +### Step-by-Step Instructions + +1. Authenticate with the GroupDocs.Viewer Cloud API +2. Specify the source file path +3. Specify the destination file path +4. Optionally specify the source and destination storage names +5. Execute the move request +6. Verify the file was successfully moved + +### cURL Example + +```bash +curl -X PUT "https://api.groupdocs.cloud/v2.0/viewer/storage/file/move/viewerdocs/source-document.docx?destPath=viewerdocs/moved-document.docx&srcStorageName=MyStorage&destStorageName=MyStorage" \ + -H "accept: application/json" \ + -H "authorization: Bearer YOUR_ACCESS_TOKEN" +``` + +### SDK Examples + +Let's implement file moving using various SDKs: + +#### C# Example + +```csharp +using GroupDocs.Viewer.Cloud.Sdk.Api; +using GroupDocs.Viewer.Cloud.Sdk.Client; +using GroupDocs.Viewer.Cloud.Sdk.Model.Requests; +using System; + +namespace GroupDocs.Viewer.Cloud.Examples +{ + class MoveFileExample + { + public static void Run() + { + // Authenticate with the API + var configuration = new Configuration(Common.MyAppSid, Common.MyAppKey); + var apiInstance = new FileApi(configuration); + + try + { + // Create move request + var request = new MoveFileRequest( + "viewerdocs/source-document.docx", // Source file path + "viewerdocs/moved-document.docx", // Destination file path + Common.MyStorage, // Source storage name + Common.MyStorage // Destination storage name + ); + + // Execute the request + apiInstance.MoveFile(request); + Console.WriteLine("File moved successfully."); + } + catch (Exception e) + { + Console.WriteLine("Error moving file: " + e.Message); + } + } + } +} +``` + +#### Java Example + +```java +package examples; + +import com.groupdocs.cloud.viewer.api.*; +import com.groupdocs.cloud.viewer.client.ApiException; +import com.groupdocs.cloud.viewer.model.requests.*; + +public class MoveFileExample { + + public static void main(String[] args) { + // Authenticate with the API + FileApi apiInstance = new FileApi(Common.AppSID, Common.AppKey); + + try { + // Create move request + MoveFileRequest request = new MoveFileRequest( + "viewerdocs/source-document.docx", // Source file path + "viewerdocs/moved-document.docx", // Destination file path + Common.MyStorage, // Source storage name + Common.MyStorage, // Destination storage name + null // Version ID (optional) + ); + + // Execute the request + apiInstance.moveFile(request); + System.out.println("File moved successfully."); + } catch (ApiException e) { + System.err.println("Error moving file: " + e.getMessage()); + e.printStackTrace(); + } + } +} +``` + +#### Python Example + +```python +import groupdocs_viewer_cloud +from groupdocs_viewer_cloud import MoveFileRequest + +# Authenticate with the API +configuration = groupdocs_viewer_cloud.Configuration(Common.app_sid, Common.app_key) +api_instance = groupdocs_viewer_cloud.FileApi(configuration) + +try: + # Create move request + request = MoveFileRequest( + "viewerdocs/source-document.docx", # Source file path + "viewerdocs/moved-document.docx", # Destination file path + Common.my_storage, # Source storage name + Common.my_storage # Destination storage name + ) + + # Execute the request + api_instance.move_file(request) + + print("File moved successfully.") + +except groupdocs_viewer_cloud.ApiException as e: + print(f"Error moving file: {e.message}") +``` + +### Try It Yourself + +1. Replace the source file path with a document in your storage +2. Replace the destination file path with your preferred path +3. Run the code and verify that the move was successful +4. Check your cloud storage dashboard to confirm the file appears in its new location and no longer exists at the original location + +## Common Issues and Troubleshooting + +When working with file operations, you might encounter these common issues: + +1. Authentication Errors + - Problem: API returns 401 Unauthorized + - Solution: Check your Client ID and Client Secret; make sure your token hasn't expired + +2. File Not Found + - Problem: API returns 404 Not Found when trying to download, delete, copy, or move a file + - Solution: Double-check the file path and storage name; verify the file exists + +3. Permission Issues + - Problem: API returns 403 Forbidden + - Solution: Verify your account has the necessary permissions for the requested operation + +4. Storage Quota Exceeded + - Problem: Upload fails with a storage quota error + - Solution: Free up space in your storage or upgrade your plan + +## What You've Learned + +In this tutorial, you've learned how to: +- Download files from your GroupDocs Cloud Storage +- Upload files to your GroupDocs Cloud Storage +- Delete files from your GroupDocs Cloud Storage +- Copy files within your GroupDocs Cloud Storage +- Move files within your GroupDocs Cloud Storage + +You now have the essential skills to manage files for your document viewing applications. + +## Further Practice + +To reinforce your learning, try these exercises: +1. Create a small application that uploads a file and then downloads it +2. Write a script that moves files from one folder to another based on file type +3. Implement a file management utility that handles bulk operations + +## Resources + +- [Product Page](https://products.groupdocs.cloud/viewer/) +- [Documentation](https://docs.groupdocs.cloud/viewer/) +- [Live Demo](https://products.groupdocs.app/viewer/family) +- [API Reference UI](https://reference.groupdocs.cloud/viewer/) +- [Blog](https://blog.groupdocs.cloud/categories/groupdocs.viewer-cloud-product-family/) +- [Free Support](https://forum.groupdocs.cloud/c/viewer/9) +- [Free Trial](https://dashboard.groupdocs.cloud/#/apps) + +Have questions about this tutorial? Feel free to reach out on our [support forum](https://forum.groupdocs.cloud/c/viewer/9). diff --git a/content/viewer/english/getting-started/working-with-folder/_index.md b/content/viewer/english/getting-started/working-with-folder/_index.md new file mode 100644 index 0000000..bce020e --- /dev/null +++ b/content/viewer/english/getting-started/working-with-folder/_index.md @@ -0,0 +1,770 @@ +--- +title: Managing Folders in GroupDocs.Viewer Cloud Tutorial +description: Learn how to manage folders in GroupDocs.Viewer Cloud with this step-by-step tutorial covering folder creation, listing, copying, moving, and deletion. +url: /getting-started/working-with-folder/ +weight: 30 +--- + +# Tutorial: Managing Folders in GroupDocs.Viewer Cloud + +## Learning Objectives + +In this tutorial, you'll learn how to: +- List files in a specific folder +- Create new folders in cloud storage +- Delete folders from cloud storage +- Copy folders within cloud storage +- Move folders within cloud storage + +## Prerequisites + +Before you begin this tutorial, you need: +- A GroupDocs Cloud account (if you don't have one, [sign up for a free trial](https://dashboard.groupdocs.cloud/#/apps)) +- Client ID and Client Secret credentials +- Basic understanding of REST APIs and your preferred programming language +- Development environment with the respective GroupDocs.Viewer Cloud SDK installed + +## Introduction + +Organizing documents effectively is crucial for any document management system. GroupDocs.Viewer Cloud provides comprehensive APIs to help you manage folders within your cloud storage. + +In this tutorial, we'll explore a practical scenario: You're developing a document portal that needs to organize documents by department, project, and document type. You'll need to create folder structures, list files within folders, and perform operations like copying, moving, and deleting folders. + +Let's learn how to implement these folder management operations using the GroupDocs.Viewer Cloud API. + +## 1. List Files in a Specific Folder + +The first operation we'll learn is listing files in a folder, which is essential for browsing document collections. + +### Step-by-Step Instructions + +1. Authenticate with the GroupDocs.Viewer Cloud API +2. Specify the folder path you want to list +3. Optionally specify the storage name +4. Execute the list request +5. Process the returned file list + +### cURL Example + +```bash +curl -X GET "https://api.groupdocs.cloud/v2.0/viewer/storage/folder/viewerdocs?storageName=MyStorage" \ + -H "accept: application/json" \ + -H "authorization: Bearer YOUR_ACCESS_TOKEN" +``` + +### SDK Examples + +Let's see how to implement file listing using various SDKs: + +#### C# Example + +```csharp +using GroupDocs.Viewer.Cloud.Sdk.Api; +using GroupDocs.Viewer.Cloud.Sdk.Client; +using GroupDocs.Viewer.Cloud.Sdk.Model.Requests; +using System; + +namespace GroupDocs.Viewer.Cloud.Examples +{ + class ListFilesExample + { + public static void Run() + { + // Authenticate with the API + var configuration = new Configuration(Common.MyAppSid, Common.MyAppKey); + var apiInstance = new FolderApi(configuration); + + try + { + // Create list files request + var request = new GetFilesListRequest( + "viewerdocs", // Folder path + Common.MyStorage // Storage name + ); + + // Execute the request + var response = apiInstance.GetFilesList(request); + + // Process the results + Console.WriteLine($"Files found: {response.Value.Count}"); + + // Print file details + foreach (var file in response.Value) + { + Console.WriteLine($"File: {file.Name}, Size: {file.Size}, Path: {file.Path}"); + } + } + catch (Exception e) + { + Console.WriteLine("Error listing files: " + e.Message); + } + } + } +} +``` + +#### Java Example + +```java +package examples; + +import com.groupdocs.cloud.viewer.api.*; +import com.groupdocs.cloud.viewer.client.ApiException; +import com.groupdocs.cloud.viewer.model.*; +import com.groupdocs.cloud.viewer.model.requests.*; + +public class ListFilesExample { + + public static void main(String[] args) { + // Authenticate with the API + FolderApi apiInstance = new FolderApi(Common.AppSID, Common.AppKey); + + try { + // Create list files request + GetFilesListRequest request = new GetFilesListRequest( + "viewerdocs", // Folder path + Common.MyStorage // Storage name + ); + + // Execute the request + FilesList response = apiInstance.getFilesList(request); + + // Process the results + System.out.println("Files found: " + response.getValue().size()); + + // Print file details + for (StorageFile file : response.getValue()) { + System.out.println("File: " + file.getName() + + ", Size: " + file.getSize() + + ", Path: " + file.getPath()); + } + } catch (ApiException e) { + System.err.println("Error listing files: " + e.getMessage()); + e.printStackTrace(); + } + } +} +``` + +#### Python Example + +```python +import groupdocs_viewer_cloud +from groupdocs_viewer_cloud import GetFilesListRequest + +# Authenticate with the API +configuration = groupdocs_viewer_cloud.Configuration(Common.app_sid, Common.app_key) +api_instance = groupdocs_viewer_cloud.FolderApi(configuration) + +try: + # Create list files request + request = GetFilesListRequest( + "viewerdocs", # Folder path + Common.my_storage # Storage name + ) + + # Execute the request + response = api_instance.get_files_list(request) + + # Process the results + print(f"Files found: {len(response.value)}") + + # Print file details + for file in response.value: + print(f"File: {file.name}, Size: {file.size}, Path: {file.path}") + +except groupdocs_viewer_cloud.ApiException as e: + print(f"Error listing files: {e.message}") +``` + +### Try It Yourself + +1. Replace the folder path with a folder in your storage +2. Run the code and verify that the list is returned successfully +3. Examine the properties of each file in the list +4. Try listing an empty folder or a non-existent folder to see how errors are handled + +## 2. Create New Folders in Cloud Storage + +Next, let's learn how to create new folders in your cloud storage, which is essential for organizing your documents. + +### Step-by-Step Instructions + +1. Authenticate with the GroupDocs.Viewer Cloud API +2. Specify the path of the folder you want to create +3. Optionally specify the storage name +4. Execute the create folder request +5. Verify the folder was created successfully + +### cURL Example + +```bash +curl -X POST "https://api.groupdocs.cloud/v2.0/viewer/storage/folder/viewerdocs/new-folder?storageName=MyStorage" \ + -H "accept: application/json" \ + -H "authorization: Bearer YOUR_ACCESS_TOKEN" +``` + +### SDK Examples + +Let's implement folder creation using various SDKs: + +#### C# Example + +```csharp +using GroupDocs.Viewer.Cloud.Sdk.Api; +using GroupDocs.Viewer.Cloud.Sdk.Client; +using GroupDocs.Viewer.Cloud.Sdk.Model.Requests; +using System; + +namespace GroupDocs.Viewer.Cloud.Examples +{ + class CreateFolderExample + { + public static void Run() + { + // Authenticate with the API + var configuration = new Configuration(Common.MyAppSid, Common.MyAppKey); + var apiInstance = new FolderApi(configuration); + + try + { + // Create folder request + var request = new CreateFolderRequest( + "viewerdocs/new-folder", // Folder path to create + Common.MyStorage // Storage name + ); + + // Execute the request + apiInstance.CreateFolder(request); + Console.WriteLine("Folder created successfully: viewerdocs/new-folder"); + } + catch (Exception e) + { + Console.WriteLine("Error creating folder: " + e.Message); + } + } + } +} +``` + +#### Java Example + +```java +package examples; + +import com.groupdocs.cloud.viewer.api.*; +import com.groupdocs.cloud.viewer.client.ApiException; +import com.groupdocs.cloud.viewer.model.requests.*; + +public class CreateFolderExample { + + public static void main(String[] args) { + // Authenticate with the API + FolderApi apiInstance = new FolderApi(Common.AppSID, Common.AppKey); + + try { + // Create folder request + CreateFolderRequest request = new CreateFolderRequest( + "viewerdocs/new-folder", // Folder path to create + Common.MyStorage // Storage name + ); + + // Execute the request + apiInstance.createFolder(request); + System.out.println("Folder created successfully: viewerdocs/new-folder"); + } catch (ApiException e) { + System.err.println("Error creating folder: " + e.getMessage()); + e.printStackTrace(); + } + } +} +``` + +#### Python Example + +```python +import groupdocs_viewer_cloud +from groupdocs_viewer_cloud import CreateFolderRequest + +# Authenticate with the API +configuration = groupdocs_viewer_cloud.Configuration(Common.app_sid, Common.app_key) +api_instance = groupdocs_viewer_cloud.FolderApi(configuration) + +try: + # Create folder request + request = CreateFolderRequest( + "viewerdocs/new-folder", # Folder path to create + Common.my_storage # Storage name + ) + + # Execute the request + api_instance.create_folder(request) + + print("Folder created successfully: viewerdocs/new-folder") + +except groupdocs_viewer_cloud.ApiException as e: + print(f"Error creating folder: {e.message}") +``` + +### Try It Yourself + +1. Replace the folder path with a new folder path in your storage +2. Run the code and verify that the folder was created successfully +3. Check your cloud storage dashboard to confirm the folder appears +4. Try creating nested folders by using paths like "viewerdocs/parent/child" + +## 3. Delete Folders from Cloud Storage + +Now, let's learn how to delete folders from your cloud storage, which is necessary for cleaning up unused resources. + +### Step-by-Step Instructions + +1. Authenticate with the GroupDocs.Viewer Cloud API +2. Specify the path of the folder you want to delete +3. Decide whether to delete recursively (including all contents) +4. Optionally specify the storage name +5. Execute the delete folder request +6. Verify the folder was deleted successfully + +### cURL Example + +```bash +curl -X DELETE "https://api.groupdocs.cloud/v2.0/viewer/storage/folder/viewerdocs/new-folder?recursive=true&storageName=MyStorage" \ + -H "accept: application/json" \ + -H "authorization: Bearer YOUR_ACCESS_TOKEN" +``` + +### SDK Examples + +Let's implement folder deletion using various SDKs: + +#### C# Example + +```csharp +using GroupDocs.Viewer.Cloud.Sdk.Api; +using GroupDocs.Viewer.Cloud.Sdk.Client; +using GroupDocs.Viewer.Cloud.Sdk.Model.Requests; +using System; + +namespace GroupDocs.Viewer.Cloud.Examples +{ + class DeleteFolderExample + { + public static void Run() + { + // Authenticate with the API + var configuration = new Configuration(Common.MyAppSid, Common.MyAppKey); + var apiInstance = new FolderApi(configuration); + + try + { + // Create delete folder request + var request = new DeleteFolderRequest( + "viewerdocs/new-folder", // Folder path to delete + Common.MyStorage, // Storage name + true // Delete recursively + ); + + // Execute the request + apiInstance.DeleteFolder(request); + Console.WriteLine("Folder deleted successfully: viewerdocs/new-folder"); + } + catch (Exception e) + { + Console.WriteLine("Error deleting folder: " + e.Message); + } + } + } +} +``` + +#### Java Example + +```java +package examples; + +import com.groupdocs.cloud.viewer.api.*; +import com.groupdocs.cloud.viewer.client.ApiException; +import com.groupdocs.cloud.viewer.model.requests.*; + +public class DeleteFolderExample { + + public static void main(String[] args) { + // Authenticate with the API + FolderApi apiInstance = new FolderApi(Common.AppSID, Common.AppKey); + + try { + // Create delete folder request + DeleteFolderRequest request = new DeleteFolderRequest( + "viewerdocs/new-folder", // Folder path to delete + Common.MyStorage, // Storage name + true // Delete recursively + ); + + // Execute the request + apiInstance.deleteFolder(request); + System.out.println("Folder deleted successfully: viewerdocs/new-folder"); + } catch (ApiException e) { + System.err.println("Error deleting folder: " + e.getMessage()); + e.printStackTrace(); + } + } +} +``` + +#### Python Example + +```python +import groupdocs_viewer_cloud +from groupdocs_viewer_cloud import DeleteFolderRequest + +# Authenticate with the API +configuration = groupdocs_viewer_cloud.Configuration(Common.app_sid, Common.app_key) +api_instance = groupdocs_viewer_cloud.FolderApi(configuration) + +try: + # Create delete folder request + request = DeleteFolderRequest( + "viewerdocs/new-folder", # Folder path to delete + Common.my_storage, # Storage name + True # Delete recursively + ) + + # Execute the request + api_instance.delete_folder(request) + + print("Folder deleted successfully: viewerdocs/new-folder") + +except groupdocs_viewer_cloud.ApiException as e: + print(f"Error deleting folder: {e.message}") +``` + +### Try It Yourself + +1. First, make sure you have a folder you can delete in your storage +2. Replace the folder path with that folder +3. Run the code and verify that the deletion was successful +4. Check your cloud storage dashboard to confirm the folder no longer appears +5. Try setting recursive to false when deleting a non-empty folder to see how the API handles it + +## 4. Copy Folders within Cloud Storage + +Let's explore how to copy folders within your cloud storage, which is useful for duplicating folder structures. + +### Step-by-Step Instructions + +1. Authenticate with the GroupDocs.Viewer Cloud API +2. Specify the source folder path +3. Specify the destination folder path +4. Optionally specify the source and destination storage names +5. Execute the copy folder request +6. Verify the folder was successfully copied + +### cURL Example + +```bash +curl -X PUT "https://api.groupdocs.cloud/v2.0/viewer/storage/folder/copy/viewerdocs/source-folder?destPath=viewerdocs/destination-folder&srcStorageName=MyStorage&destStorageName=MyStorage" \ + -H "accept: application/json" \ + -H "authorization: Bearer YOUR_ACCESS_TOKEN" +``` + +### SDK Examples + +Let's implement folder copying using various SDKs: + +#### C# Example + +```csharp +using GroupDocs.Viewer.Cloud.Sdk.Api; +using GroupDocs.Viewer.Cloud.Sdk.Client; +using GroupDocs.Viewer.Cloud.Sdk.Model.Requests; +using System; + +namespace GroupDocs.Viewer.Cloud.Examples +{ + class CopyFolderExample + { + public static void Run() + { + // Authenticate with the API + var configuration = new Configuration(Common.MyAppSid, Common.MyAppKey); + var apiInstance = new FolderApi(configuration); + + try + { + // Create copy folder request + var request = new CopyFolderRequest( + "viewerdocs/source-folder", // Source folder path + "viewerdocs/destination-folder", // Destination folder path + Common.MyStorage, // Source storage name + Common.MyStorage // Destination storage name + ); + + // Execute the request + apiInstance.CopyFolder(request); + Console.WriteLine("Folder copied successfully from viewerdocs/source-folder to viewerdocs/destination-folder"); + } + catch (Exception e) + { + Console.WriteLine("Error copying folder: " + e.Message); + } + } + } +} +``` + +#### Java Example + +```java +package examples; + +import com.groupdocs.cloud.viewer.api.*; +import com.groupdocs.cloud.viewer.client.ApiException; +import com.groupdocs.cloud.viewer.model.requests.*; + +public class CopyFolderExample { + + public static void main(String[] args) { + // Authenticate with the API + FolderApi apiInstance = new FolderApi(Common.AppSID, Common.AppKey); + + try { + // Create copy folder request + CopyFolderRequest request = new CopyFolderRequest( + "viewerdocs/source-folder", // Source folder path + "viewerdocs/destination-folder", // Destination folder path + Common.MyStorage, // Source storage name + Common.MyStorage // Destination storage name + ); + + // Execute the request + apiInstance.copyFolder(request); + System.out.println("Folder copied successfully from viewerdocs/source-folder to viewerdocs/destination-folder"); + } catch (ApiException e) { + System.err.println("Error copying folder: " + e.getMessage()); + e.printStackTrace(); + } + } +} +``` + +#### Python Example + +```python +import groupdocs_viewer_cloud +from groupdocs_viewer_cloud import CopyFolderRequest + +# Authenticate with the API +configuration = groupdocs_viewer_cloud.Configuration(Common.app_sid, Common.app_key) +api_instance = groupdocs_viewer_cloud.FolderApi(configuration) + +try: + # Create copy folder request + request = CopyFolderRequest( + "viewerdocs/source-folder", # Source folder path + "viewerdocs/destination-folder", # Destination folder path + Common.my_storage, # Source storage name + Common.my_storage # Destination storage name + ) + + # Execute the request + api_instance.copy_folder(request) + + print("Folder copied successfully from viewerdocs/source-folder to viewerdocs/destination-folder") + +except groupdocs_viewer_cloud.ApiException as e: + print(f"Error copying folder: {e.message}") +``` + +### Try It Yourself + +1. First, make sure you have a source folder in your storage +2. Replace the source and destination paths with your preferred paths +3. Run the code and verify that the copy was successful +4. Check your cloud storage dashboard to confirm both folders appear with identical contents + +## 5. Move Folders within Cloud Storage + +Finally, let's learn how to move folders within your cloud storage, which is useful for reorganizing your folder structure. + +### Step-by-Step Instructions + +1. Authenticate with the GroupDocs.Viewer Cloud API +2. Specify the source folder path +3. Specify the destination folder path +4. Optionally specify the source and destination storage names +5. Execute the move folder request +6. Verify the folder was successfully moved + +### cURL Example + +```bash +curl -X PUT "https://api.groupdocs.cloud/v2.0/viewer/storage/folder/move/viewerdocs/source-folder?destPath=viewerdocs/moved-folder&srcStorageName=MyStorage&destStorageName=MyStorage" \ + -H "accept: application/json" \ + -H "authorization: Bearer YOUR_ACCESS_TOKEN" +``` + +### SDK Examples + +Let's implement folder moving using various SDKs: + +#### C# Example + +```csharp +using GroupDocs.Viewer.Cloud.Sdk.Api; +using GroupDocs.Viewer.Cloud.Sdk.Client; +using GroupDocs.Viewer.Cloud.Sdk.Model.Requests; +using System; + +namespace GroupDocs.Viewer.Cloud.Examples +{ + class MoveFolderExample + { + public static void Run() + { + // Authenticate with the API + var configuration = new Configuration(Common.MyAppSid, Common.MyAppKey); + var apiInstance = new FolderApi(configuration); + + try + { + // Create move folder request + var request = new MoveFolderRequest( + "viewerdocs/source-folder", // Source folder path + "viewerdocs/moved-folder", // Destination folder path + Common.MyStorage, // Source storage name + Common.MyStorage // Destination storage name + ); + + // Execute the request + apiInstance.MoveFolder(request); + Console.WriteLine("Folder moved successfully from viewerdocs/source-folder to viewerdocs/moved-folder"); + } + catch (Exception e) + { + Console.WriteLine("Error moving folder: " + e.Message); + } + } + } +} +``` + +#### Java Example + +```java +package examples; + +import com.groupdocs.cloud.viewer.api.*; +import com.groupdocs.cloud.viewer.client.ApiException; +import com.groupdocs.cloud.viewer.model.requests.*; + +public class MoveFolderExample { + + public static void main(String[] args) { + // Authenticate with the API + FolderApi apiInstance = new FolderApi(Common.AppSID, Common.AppKey); + + try { + // Create move folder request + MoveFolderRequest request = new MoveFolderRequest( + "viewerdocs/source-folder", // Source folder path + "viewerdocs/moved-folder", // Destination folder path + Common.MyStorage, // Source storage name + Common.MyStorage // Destination storage name + ); + + // Execute the request + apiInstance.moveFolder(request); + System.out.println("Folder moved successfully from viewerdocs/source-folder to viewerdocs/moved-folder"); + } catch (ApiException e) { + System.err.println("Error moving folder: " + e.getMessage()); + e.printStackTrace(); + } + } +} +``` + +#### Python Example + +```python +import groupdocs_viewer_cloud +from groupdocs_viewer_cloud import MoveFolderRequest + +# Authenticate with the API +configuration = groupdocs_viewer_cloud.Configuration(Common.app_sid, Common.app_key) +api_instance = groupdocs_viewer_cloud.FolderApi(configuration) + +try: + # Create move folder request + request = MoveFolderRequest( + "viewerdocs/source-folder", # Source folder path + "viewerdocs/moved-folder", # Destination folder path + Common.my_storage, # Source storage name + Common.my_storage # Destination storage name + ) + + # Execute the request + api_instance.move_folder(request) + + print("Folder moved successfully from viewerdocs/source-folder to viewerdocs/moved-folder") + +except groupdocs_viewer_cloud.ApiException as e: + print(f"Error moving folder: {e.message}") +``` + +### Try It Yourself + +1. First, make sure you have a source folder in your storage +2. Replace the source and destination paths with your preferred paths +3. Run the code and verify that the move was successful +4. Check your cloud storage dashboard to confirm the folder appears in its new location and no longer exists at the original location + +## Common Issues and Troubleshooting + +When working with folder operations, you might encounter these common issues: + +1. Authentication Errors + - Problem: API returns 401 Unauthorized + - Solution: Check your Client ID and Client Secret; make sure your token hasn't expired + +2. Folder Not Found + - Problem: API returns 404 Not Found when trying to list, delete, copy, or move a folder + - Solution: Double-check the folder path and storage name; verify the folder exists + +3. Folder Already Exists + - Problem: API returns an error when creating a folder that already exists + - Solution: Check if the folder exists before creating it, or handle the exception appropriately + +4. Permission Issues + - Problem: API returns 403 Forbidden + - Solution: Verify your account has the necessary permissions for the requested operation + +## What You've Learned + +In this tutorial, you've learned how to: +- List files in a specific folder +- Create new folders in your GroupDocs Cloud Storage +- Delete folders from your GroupDocs Cloud Storage +- Copy folders within your GroupDocs Cloud Storage +- Move folders within your GroupDocs Cloud Storage + +You now have the essential skills to manage folders for your document viewing applications. + +## Further Practice + +To reinforce your learning, try these exercises: +1. Create a simple folder browser application that lists and navigates through folders +2. Implement a recursive function that creates a multi-level folder structure +3. Write a utility that synchronizes folders between different storage locations + +## Resources + +- [Product Page](https://products.groupdocs.cloud/viewer/) +- [Documentation](https://docs.groupdocs.cloud/viewer/) +- [Live Demo](https://products.groupdocs.app/viewer/family) +- [API Reference UI](https://reference.groupdocs.cloud/viewer/) +- [Blog](https://blog.groupdocs.cloud/categories/groupdocs.viewer-cloud-product-family/) +- [Free Support](https://forum.groupdocs.cloud/c/viewer/9) +- [Free Trial](https://dashboard.groupdocs.cloud/#/apps) + +Have questions about this tutorial? Feel free to reach out on our [support forum](https://forum.groupdocs.cloud/c/viewer/9). \ No newline at end of file diff --git a/content/viewer/english/getting-started/working-with-storage/_index.md b/content/viewer/english/getting-started/working-with-storage/_index.md new file mode 100644 index 0000000..2e74142 --- /dev/null +++ b/content/viewer/english/getting-started/working-with-storage/_index.md @@ -0,0 +1,699 @@ +--- +title: Working with Storage in GroupDocs.Viewer Cloud Tutorial +description: Learn how to manage cloud storage in GroupDocs.Viewer Cloud with this step-by-step tutorial covering storage operations, checking existence, and monitoring usage. +url: /getting-started/working-with-storage/ +weight: 40 +--- + + +# Tutorial: Working with Storage in GroupDocs.Viewer Cloud + +## Learning Objectives + +In this tutorial, you'll learn how to: +- Check if a storage exists in GroupDocs Cloud +- Verify if a file or folder exists in cloud storage +- Monitor storage space usage +- Retrieve file versions information + +## Prerequisites + +Before you begin this tutorial, you need: +- A GroupDocs Cloud account (if you don't have one, [sign up for a free trial](https://dashboard.groupdocs.cloud/#/apps)) +- Client ID and Client Secret credentials +- Basic understanding of REST APIs and your preferred programming language +- Development environment with the respective GroupDocs.Viewer Cloud SDK installed + +## Introduction + +Efficient storage management is crucial for any document viewing application. GroupDocs.Viewer Cloud provides comprehensive APIs to monitor and manage your cloud storage resources. + +In this tutorial, we'll explore a practical scenario: You're developing an enterprise document management system and need to implement features to monitor storage usage, check file existence before operations, and manage document versions. + +Let's learn how to implement these storage management operations using the GroupDocs.Viewer Cloud API. + +## 1. Check If Storage Exists + +First, let's learn how to check if a specific storage exists in your GroupDocs Cloud account, which is useful when working with multiple storage locations. + +### Step-by-Step Instructions + +1. Authenticate with the GroupDocs.Viewer Cloud API +2. Specify the storage name you want to check +3. Execute the storage existence request +4. Process the boolean result indicating whether the storage exists + +### cURL Example + +```bash +curl -X GET "https://api.groupdocs.cloud/v2.0/viewer/storage/MyStorage/exist" \ + -H "accept: application/json" \ + -H "authorization: Bearer YOUR_ACCESS_TOKEN" +``` + +### SDK Examples + +Let's see how to check storage existence using various SDKs: + +#### C# Example + +```csharp +using GroupDocs.Viewer.Cloud.Sdk.Api; +using GroupDocs.Viewer.Cloud.Sdk.Client; +using GroupDocs.Viewer.Cloud.Sdk.Model.Requests; +using System; + +namespace GroupDocs.Viewer.Cloud.Examples +{ + class CheckStorageExistExample + { + public static void Run() + { + // Authenticate with the API + var configuration = new Configuration(Common.MyAppSid, Common.MyAppKey); + var apiInstance = new StorageApi(configuration); + + try + { + // Create storage existence request + var request = new StorageExistsRequest(Common.MyStorage); + + // Execute the request + var response = apiInstance.StorageExists(request); + + // Process the result + Console.WriteLine($"Storage '{Common.MyStorage}' exists: {response.Exists}"); + } + catch (Exception e) + { + Console.WriteLine("Error checking storage existence: " + e.Message); + } + } + } +} +``` + +#### Java Example + +```java +package examples; + +import com.groupdocs.cloud.viewer.api.*; +import com.groupdocs.cloud.viewer.client.ApiException; +import com.groupdocs.cloud.viewer.model.*; +import com.groupdocs.cloud.viewer.model.requests.*; + +public class CheckStorageExistExample { + + public static void main(String[] args) { + // Authenticate with the API + StorageApi apiInstance = new StorageApi(Common.AppSID, Common.AppKey); + + try { + // Create storage existence request + StorageExistsRequest request = new StorageExistsRequest(Common.MyStorage); + + // Execute the request + StorageExist response = apiInstance.storageExists(request); + + // Process the result + System.out.println("Storage '" + Common.MyStorage + "' exists: " + response.getExists()); + } catch (ApiException e) { + System.err.println("Error checking storage existence: " + e.getMessage()); + e.printStackTrace(); + } + } +} +``` + +#### Python Example + +```python +import groupdocs_viewer_cloud +from groupdocs_viewer_cloud import StorageExistsRequest + +# Authenticate with the API +configuration = groupdocs_viewer_cloud.Configuration(Common.app_sid, Common.app_key) +api_instance = groupdocs_viewer_cloud.StorageApi(configuration) + +try: + # Create storage existence request + request = StorageExistsRequest(Common.my_storage) + + # Execute the request + response = api_instance.storage_exists(request) + + # Process the result + print(f"Storage '{Common.my_storage}' exists: {response.exists}") + +except groupdocs_viewer_cloud.ApiException as e: + print(f"Error checking storage existence: {e.message}") +``` + +### Try It Yourself + +1. Replace the storage name with your actual storage name +2. Run the code and verify that the check was successful +3. Try checking for a non-existent storage name to see how the API handles it +4. Use this method to verify storage availability before performing operations + +## 2. Check If File or Folder Exists + +Next, let's learn how to check if a specific file or folder exists in your cloud storage, which is essential before performing operations on them. + +### Step-by-Step Instructions + +1. Authenticate with the GroupDocs.Viewer Cloud API +2. Specify the path of the file or folder you want to check +3. Optionally specify the storage name +4. Execute the object existence request +5. Process the boolean result and additional information about the object + +### cURL Example + +```bash +curl -X GET "https://api.groupdocs.cloud/v2.0/viewer/storage/exist/viewerdocs/document.docx?storageName=MyStorage" \ + -H "accept: application/json" \ + -H "authorization: Bearer YOUR_ACCESS_TOKEN" +``` + +### SDK Examples + +Let's see how to check if a file or folder exists using various SDKs: + +#### C# Example + +```csharp +using GroupDocs.Viewer.Cloud.Sdk.Api; +using GroupDocs.Viewer.Cloud.Sdk.Client; +using GroupDocs.Viewer.Cloud.Sdk.Model.Requests; +using System; + +namespace GroupDocs.Viewer.Cloud.Examples +{ + class CheckObjectExistsExample + { + public static void Run() + { + // Authenticate with the API + var configuration = new Configuration(Common.MyAppSid, Common.MyAppKey); + var apiInstance = new StorageApi(configuration); + + try + { + // Create object existence request + var request = new ObjectExistsRequest( + "viewerdocs/document.docx", // Object path + Common.MyStorage // Storage name + ); + + // Execute the request + var response = apiInstance.ObjectExists(request); + + // Process the result + Console.WriteLine($"Object exists: {response.Exists}"); + if (response.Exists) + { + Console.WriteLine($"Is folder: {response.IsFolder}"); + } + } + catch (Exception e) + { + Console.WriteLine("Error checking object existence: " + e.Message); + } + } + } +} +``` + +#### Java Example + +```java +package examples; + +import com.groupdocs.cloud.viewer.api.*; +import com.groupdocs.cloud.viewer.client.ApiException; +import com.groupdocs.cloud.viewer.model.*; +import com.groupdocs.cloud.viewer.model.requests.*; + +public class CheckObjectExistsExample { + + public static void main(String[] args) { + // Authenticate with the API + StorageApi apiInstance = new StorageApi(Common.AppSID, Common.AppKey); + + try { + // Create object existence request + ObjectExistsRequest request = new ObjectExistsRequest( + "viewerdocs/document.docx", // Object path + Common.MyStorage, // Storage name + null // Version ID (optional) + ); + + // Execute the request + ObjectExist response = apiInstance.objectExists(request); + + // Process the result + System.out.println("Object exists: " + response.getExists()); + if (response.getExists()) { + System.out.println("Is folder: " + response.getIsFolder()); + } + } catch (ApiException e) { + System.err.println("Error checking object existence: " + e.getMessage()); + e.printStackTrace(); + } + } +} +``` + +#### Python Example + +```python +import groupdocs_viewer_cloud +from groupdocs_viewer_cloud import ObjectExistsRequest + +# Authenticate with the API +configuration = groupdocs_viewer_cloud.Configuration(Common.app_sid, Common.app_key) +api_instance = groupdocs_viewer_cloud.StorageApi(configuration) + +try: + # Create object existence request + request = ObjectExistsRequest( + "viewerdocs/document.docx", # Object path + Common.my_storage # Storage name + ) + + # Execute the request + response = api_instance.object_exists(request) + + # Process the result + print(f"Object exists: {response.exists}") + if response.exists: + print(f"Is folder: {response.is_folder}") + +except groupdocs_viewer_cloud.ApiException as e: + print(f"Error checking object existence: {e.message}") +``` + +### Try It Yourself + +1. Replace the object path with a file or folder in your storage +2. Run the code and verify the existence check was successful +3. Test with both files and folders to see the different responses +4. Try checking for non-existent objects to see how the API handles it + +## 3. Monitor Storage Space Usage + +Now, let's learn how to monitor storage space usage, which is essential for managing your storage resources efficiently. + +### Step-by-Step Instructions + +1. Authenticate with the GroupDocs.Viewer Cloud API +2. Optionally specify the storage name for which to check usage +3. Execute the disc usage request +4. Process the response containing total and used storage space information + +### cURL Example + +```bash +curl -X GET "https://api.groupdocs.cloud/v2.0/viewer/storage/disc?storageName=MyStorage" \ + -H "accept: application/json" \ + -H "authorization: Bearer YOUR_ACCESS_TOKEN" +``` + +### SDK Examples + +Let's see how to monitor storage space usage using various SDKs: + +#### C# Example + +```csharp +using GroupDocs.Viewer.Cloud.Sdk.Api; +using GroupDocs.Viewer.Cloud.Sdk.Client; +using GroupDocs.Viewer.Cloud.Sdk.Model.Requests; +using System; + +namespace GroupDocs.Viewer.Cloud.Examples +{ + class GetDiscUsageExample + { + public static void Run() + { + // Authenticate with the API + var configuration = new Configuration(Common.MyAppSid, Common.MyAppKey); + var apiInstance = new StorageApi(configuration); + + try + { + // Create disc usage request + var request = new GetDiscUsageRequest(Common.MyStorage); + + // Execute the request + var response = apiInstance.GetDiscUsage(request); + + // Process the result + Console.WriteLine($"Total space: {FormatSize(response.TotalSize)} bytes"); + Console.WriteLine($"Used space: {FormatSize(response.UsedSize)} bytes"); + + // Calculate percentage used + var percentUsed = (double)response.UsedSize / response.TotalSize * 100; + Console.WriteLine($"Usage: {percentUsed:F2}%"); + } + catch (Exception e) + { + Console.WriteLine("Error getting disc usage: " + e.Message); + } + } + + // Helper method to format size for readability + private static string FormatSize(long bytes) + { + string[] sizes = { "B", "KB", "MB", "GB", "TB" }; + double len = bytes; + int order = 0; + while (len >= 1024 && order < sizes.Length - 1) { + order++; + len = len / 1024; + } + return String.Format("{0:0.##} {1}", len, sizes[order]); + } + } +} +``` + +#### Java Example + +```java +package examples; + +import com.groupdocs.cloud.viewer.api.*; +import com.groupdocs.cloud.viewer.client.ApiException; +import com.groupdocs.cloud.viewer.model.*; +import com.groupdocs.cloud.viewer.model.requests.*; +import java.text.DecimalFormat; + +public class GetDiscUsageExample { + + public static void main(String[] args) { + // Authenticate with the API + StorageApi apiInstance = new StorageApi(Common.AppSID, Common.AppKey); + + try { + // Create disc usage request + GetDiscUsageRequest request = new GetDiscUsageRequest(Common.MyStorage); + + // Execute the request + DiscUsage response = apiInstance.getDiscUsage(request); + + // Process the result + System.out.println("Total space: " + formatSize(response.getTotalSize()) + " bytes"); + System.out.println("Used space: " + formatSize(response.getUsedSize()) + " bytes"); + + // Calculate percentage used + double percentUsed = (double) response.getUsedSize() / response.getTotalSize() * 100; + DecimalFormat df = new DecimalFormat("#.##"); + System.out.println("Usage: " + df.format(percentUsed) + "%"); + } catch (ApiException e) { + System.err.println("Error getting disc usage: " + e.getMessage()); + e.printStackTrace(); + } + } + + // Helper method to format size for readability + private static String formatSize(long bytes) { + String[] sizes = { "B", "KB", "MB", "GB", "TB" }; + double len = bytes; + int order = 0; + while (len >= 1024 && order < sizes.length - 1) { + order++; + len = len / 1024; + } + DecimalFormat df = new DecimalFormat("#.##"); + return df.format(len) + " " + sizes[order]; + } +} +``` + +#### Python Example + +```python +import groupdocs_viewer_cloud +from groupdocs_viewer_cloud import GetDiscUsageRequest + +# Authenticate with the API +configuration = groupdocs_viewer_cloud.Configuration(Common.app_sid, Common.app_key) +api_instance = groupdocs_viewer_cloud.StorageApi(configuration) + +try: + # Create disc usage request + request = GetDiscUsageRequest(Common.my_storage) + + # Execute the request + response = api_instance.get_disc_usage(request) + + # Process the result + print(f"Total space: {format_size(response.total_size)}") + print(f"Used space: {format_size(response.used_size)}") + + # Calculate percentage used + percent_used = (response.used_size / response.total_size) * 100 + print(f"Usage: {percent_used:.2f}%") + +except groupdocs_viewer_cloud.ApiException as e: + print(f"Error getting disc usage: {e.message}") + +# Helper function to format size for readability +def format_size(bytes): + sizes = ["B", "KB", "MB", "GB", "TB"] + i = 0 + while bytes >= 1024 and i < len(sizes) - 1: + bytes /= 1024 + i += 1 + return f"{bytes:.2f} {sizes[i]}" +``` + +### Try It Yourself + +1. Run the code to check your storage usage +2. Compare the results with your account dashboard +3. Use the formatted size for better readability +4. Implement monitoring logic that alerts when storage usage exceeds a threshold (e.g., 80%) + +## 4. Retrieve File Versions Information + +Finally, let's learn how to retrieve information about file versions in your cloud storage, which is useful for version control in document management systems. + +### Step-by-Step Instructions + +1. Authenticate with the GroupDocs.Viewer Cloud API +2. Specify the file path for which to retrieve versions +3. Optionally specify the storage name +4. Execute the file versions request +5. Process the response containing version information for the file + +### cURL Example + +```bash +curl -X GET "https://api.groupdocs.cloud/v2.0/viewer/storage/version/viewerdocs/document.docx?storageName=MyStorage" \ + -H "accept: application/json" \ + -H "authorization: Bearer YOUR_ACCESS_TOKEN" +``` + +### SDK Examples + +Let's see how to retrieve file versions using various SDKs: + +#### C# Example + +```csharp +using GroupDocs.Viewer.Cloud.Sdk.Api; +using GroupDocs.Viewer.Cloud.Sdk.Client; +using GroupDocs.Viewer.Cloud.Sdk.Model.Requests; +using System; + +namespace GroupDocs.Viewer.Cloud.Examples +{ + class GetFileVersionsExample + { + public static void Run() + { + // Authenticate with the API + var configuration = new Configuration(Common.MyAppSid, Common.MyAppKey); + var apiInstance = new StorageApi(configuration); + + try + { + // Create file versions request + var request = new GetFileVersionsRequest( + "viewerdocs/document.docx", // File path + Common.MyStorage // Storage name + ); + + // Execute the request + var response = apiInstance.GetFileVersions(request); + + // Process the result + Console.WriteLine($"File versions count: {response.Value.Count}"); + + // Print version details + foreach (var version in response.Value) + { + Console.WriteLine($"Version: {version.VersionId}"); + Console.WriteLine($" Is latest: {version.IsLatest}"); + Console.WriteLine($" Name: {version.Name}"); + Console.WriteLine($" Modified date: {version.ModifiedDate}"); + Console.WriteLine($" Size: {version.Size} bytes"); + Console.WriteLine($" Path: {version.Path}"); + Console.WriteLine(); + } + } + catch (Exception e) + { + Console.WriteLine("Error getting file versions: " + e.Message); + } + } + } +} +``` + +#### Java Example + +```java +package examples; + +import com.groupdocs.cloud.viewer.api.*; +import com.groupdocs.cloud.viewer.client.ApiException; +import com.groupdocs.cloud.viewer.model.*; +import com.groupdocs.cloud.viewer.model.requests.*; + +public class GetFileVersionsExample { + + public static void main(String[] args) { + // Authenticate with the API + StorageApi apiInstance = new StorageApi(Common.AppSID, Common.AppKey); + + try { + // Create file versions request + GetFileVersionsRequest request = new GetFileVersionsRequest( + "viewerdocs/document.docx", // File path + Common.MyStorage // Storage name + ); + + // Execute the request + FileVersions response = apiInstance.getFileVersions(request); + + // Process the result + System.out.println("File versions count: " + response.getValue().size()); + + // Print version details + for (FileVersion version : response.getValue()) { + System.out.println("Version: " + version.getVersionId()); + System.out.println(" Is latest: " + version.getIsLatest()); + System.out.println(" Name: " + version.getName()); + System.out.println(" Modified date: " + version.getModifiedDate()); + System.out.println(" Size: " + version.getSize() + " bytes"); + System.out.println(" Path: " + version.getPath()); + System.out.println(); + } + } catch (ApiException e) { + System.err.println("Error getting file versions: " + e.getMessage()); + e.printStackTrace(); + } + } +} +``` + +#### Python Example + +```python +import groupdocs_viewer_cloud +from groupdocs_viewer_cloud import GetFileVersionsRequest + +# Authenticate with the API +configuration = groupdocs_viewer_cloud.Configuration(Common.app_sid, Common.app_key) +api_instance = groupdocs_viewer_cloud.StorageApi(configuration) + +try: + # Create file versions request + request = GetFileVersionsRequest( + "viewerdocs/document.docx", # File path + Common.my_storage # Storage name + ) + + # Execute the request + response = api_instance.get_file_versions(request) + + # Process the result + print(f"File versions count: {len(response.value)}") + + # Print version details + for version in response.value: + print(f"Version: {version.version_id}") + print(f" Is latest: {version.is_latest}") + print(f" Name: {version.name}") + print(f" Modified date: {version.modified_date}") + print(f" Size: {version.size} bytes") + print(f" Path: {version.path}") + print() + +except groupdocs_viewer_cloud.ApiException as e: + print(f"Error getting file versions: {e.message}") +``` + +### Try It Yourself + +1. Replace the file path with a document in your storage +2. Run the code and verify that the version information is retrieved +3. Try with a file that has multiple versions to see the complete version history +4. Implement version comparison or reversion logic based on the retrieved information + +## Common Issues and Troubleshooting + +When working with storage operations, you might encounter these common issues: + +1. Authentication Errors + - Problem: API returns 401 Unauthorized + - Solution: Check your Client ID and Client Secret; make sure your token hasn't expired + +2. Storage Not Found + - Problem: API returns an error when specifying a non-existent storage + - Solution: Verify the storage name; only use storage names that exist in your account + +3. Permission Issues + - Problem: API returns 403 Forbidden when accessing storage information + - Solution: Verify your account has the necessary permissions for the storage operations + +4. Rate Limiting + - Problem: Too frequent API calls result in rate limiting + - Solution: Implement caching for storage information and throttle API requests + +## What You've Learned + +In this tutorial, you've learned how to: +- Check if a specific storage exists in your GroupDocs Cloud account +- Verify if a file or folder exists in your cloud storage +- Monitor storage space usage to manage resources efficiently +- Retrieve file versions information for version control + +You now have the essential skills to implement robust storage management features in your document viewing applications. + +## Further Practice + +To reinforce your learning, try these exercises: +1. Create a storage dashboard that displays usage statistics and alerts +2. Implement a version control system that tracks document changes +3. Build a storage explorer that checks object existence before operations +4. Write a utility that manages storage resources across multiple storage locations + + +## Resources + +- [Product Page](https://products.groupdocs.cloud/viewer/) +- [Documentation](https://docs.groupdocs.cloud/viewer/) +- [Live Demo](https://products.groupdocs.app/viewer/family) +- [API Reference UI](https://reference.groupdocs.cloud/viewer/) +- [Blog](https://blog.groupdocs.cloud/categories/groupdocs.viewer-cloud-product-family/) +- [Free Support](https://forum.groupdocs.cloud/c/viewer/9) +- [Free Trial](https://dashboard.groupdocs.cloud/#/apps) + +Have questions about this tutorial? Feel free to reach out on our [support forum](https://forum.groupdocs.cloud/c/viewer/9). \ No newline at end of file