SoFunction
Updated on 2025-04-14

Vue3 implements HTML content preview function

1. Functional panoramic view

This preview component implements the following core capabilities:

✅Real restore Word layout effects

✅ Zero dependency pure front-end implementation

✅ Automatic memory recovery mechanism

✅ Responsive container support

✅ Print style optimization

2. Core implementation analysis

1. Component structure design

<template>
  <div class="preview-container">
    <iframe ref="iframeRef" 
           style="width: 100%; height: 600px"
           frameborder="0">
    </iframe>
  </div>
</template>

<script setup>
// The core logic will be broken down below</script>

2. Key technology stack

Technical points Description of function
Blob API Create a local temporary file
iframe quarantine Safely render external content
CSS Page Media Print style control
Vue Composition API Responsive data management

3. Core code implementation

1. HTML content generation

const generateFullHTML = (content) => `
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <style>
    body {
      font-family: Fang Zheng imitates Song_GBK, serif;
      margin: 2cm; /* Word standard margin */
      line-height: 1.5;
    }
    @page {
      size: A4 portrait; /* Standard A4 paper */
      margin: 2cm;       /* Print margin */
    }
  </style>
</head>
<body>${content}</body>
</html>

Design points:

  • Use Chinese font stack to ensure consistency in typesetting
  • Control the print style with @page
  • Set centimeter units to achieve real physical dimensions

2. Blob file processing

const previewHtmlAsWord = async () => {
  // Clean up old blobs  if (currentBlobUrl) (currentBlobUrl);
  
  // Generate new content  const htmlContent = generateFullHTML((''));
  const blob = new Blob([htmlContent], { 
    type: 'text/html;charset=utf-8' 
  });
  
  // Create a temporary URL  currentBlobUrl = (blob);
   = currentBlobUrl;
}

Memory security mechanism:

Clean up old blobs before each build

Automatically recycle resources when component uninstallation

Use try/catch to wrap key actions

3. Lifecycle Management

onUnmounted(() => {
  if (currentBlobUrl) {
    (currentBlobUrl); // important!  }
})

4. Advanced optimization skills

1. Printing experience optimization

@media print {
  body {
    margin: 0 !important; /* Disable the browser default margin */
  }
  .noprint {
    display: none; /* Hide non-essential elements */
  }
}

2. Safety protection measures

// Add sandbox attributes when iframe loads = 'allow-same-origin allow-scripts';

3. Performance optimization solution

// Use anti-shake to avoid frequent updatesconst debouncedPreview = debounce(previewHtmlAsWord, 300);

watch(() => , debouncedPreview, { deep: true });

V. Component communication design

1. Parent component call example

<template>
  <PreviewComponent ref="previewRef" :list="contentList" />
  <button @click="()">Generate a preview</button>
</template>

<script setup>
const previewRef = ref(null);
</script>

2. Exposure method definition

// Subcomponents expose interfacedefineExpose({
  previewHtmlAsWord // Explicit preview method});

7. Plan comparison

plan advantage shortcoming
This plan (Blob) Zero dependency, fully controllable Manual memory management is required
Professional PDF rendering Larger package
Google Docs API Perfect compatibility Requires network request

8. Summary

The preview component implemented through this article has the following advantages:

🚀 Excellent performance: local processing does not require network

🔒 Safe and reliable: sandbox isolation + automatic memory recovery

📑 Professional presentation: Perfectly restore Word layout

🔄 Easy to integrate: a component solution out of the box

This is the end of this article about Vue3 implementing HTML content preview function. For more information about Vue3 preview HTML content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!